Compare commits

...

700 Commits

Author SHA1 Message Date
Daniel Lemire 5d355f1a8b release candidate (#1132) 2020-08-19 18:12:23 -04:00
John Keiser 2ff91103ca Remove SIMDJSON_DO_NOT_USE_THREADS_NO_MATTER_WHAT (#1131) 2020-08-19 17:11:13 -04:00
Daniel Lemire a954d50ad4 This improves our documentation. (#1128)
* This improves our documentation.

* Removing tags for doxygen.

* You need a recent cmake remark.
2020-08-19 14:02:08 -04:00
John Keiser 5be4d37aff Merge pull request #1129 from simdjson/jkeiser/inl
Move inline/* to *-inl.h
2020-08-19 09:52:34 -07:00
John Keiser 1e6c9dbcfa Reamalgamate 2020-08-19 09:16:25 -07:00
John Keiser 708a56872d Move inline/* to *-inl.h 2020-08-19 09:09:31 -07:00
John Keiser 0a2bca3f73 Merge pull request #1101 from simdjson/jkeiser/yakety-sax
Basic SAX interface with benchmarks
2020-08-19 09:05:44 -07:00
Daniel Lemire 1ec710c985 Updating the documentation for hackers. 2020-08-19 10:59:24 -04:00
Daniel Lemire d5a44f9ad4 Merge branch 'master' of github.com:simdjson/simdjson 2020-08-19 10:36:01 -04:00
Daniel Lemire e64dca7144 Tweaking. 2020-08-19 10:35:49 -04:00
John Keiser b2779c35df Fix issue with unsupported unreachable on Windows 2020-08-18 21:35:12 -07:00
John Keiser 9b11e119d4 Make skip_double() comment more explicit 2020-08-18 21:25:03 -07:00
John Keiser 988c62baed Encapsulate significant_digits() 2020-08-18 21:25:03 -07:00
John Keiser eb3e640003 Return bool from compute_float_64 2020-08-18 21:25:03 -07:00
John Keiser 9475b947f5 Return error codes from parse_number 2020-08-18 21:25:03 -07:00
John Keiser 18564f1ae2 Don't benchmark unless haswell is available 2020-08-18 21:25:03 -07:00
John Keiser 638f1deb62 Add DOM tweet reader for comparison 2020-08-18 21:25:03 -07:00
John Keiser 7e74d30f45 [WIP] tweet reader SAX benchmark 2020-08-18 21:25:03 -07:00
John Keiser ce8d0f8135 Add visit_primitive() helper in iterator 2020-08-18 21:25:03 -07:00
John Keiser 872127b722 Move is_array management together with depth 2020-08-18 21:25:03 -07:00
John Keiser e180dc44bc Move container logging into json_iterator 2020-08-18 21:25:03 -07:00
John Keiser 268b8845a9 Document tape_builder 2020-08-18 21:25:03 -07:00
John Keiser 74c47995a3 Document json_iterator 2020-08-18 21:25:03 -07:00
John Keiser 24f5936cbf Give is_array responsibility to json_iterator 2020-08-18 21:25:03 -07:00
John Keiser bdfa8aca28 Separate interface from implementation to make interface clearer 2020-08-18 21:25:03 -07:00
John Keiser 15eb1ad922 Preface visitor methods with visit() 2020-08-18 21:25:03 -07:00
John Keiser 6ec98ee8b1 Add error codes to all things 2020-08-18 21:25:03 -07:00
John Keiser c5862d6de9 Remove empty_object/empty_array 2020-08-18 21:25:03 -07:00
John Keiser 57eb55446f Cache string value locally 2020-08-18 21:25:03 -07:00
John Keiser abd1399a7f Don't check depth at the end (unnecessary check) 2020-08-18 21:25:03 -07:00
John Keiser 57eba21ee5 Fall through goto labels where possible 2020-08-18 21:25:03 -07:00
John Keiser 1b56211a70 Give start_*/end_* error codes 2020-08-18 21:25:03 -07:00
John Keiser d8974d53b2 Keep value around between states 2020-08-18 21:25:03 -07:00
John Keiser 5ecd17f49e Log unconsumed input as an error 2020-08-18 21:25:03 -07:00
John Keiser 6bb99aec3c Merge structural_parser+iterator into json_iterator 2020-08-18 21:25:03 -07:00
John Keiser a67e83e24e Remove parse_* from visitor method names 2020-08-18 21:25:03 -07:00
John Keiser 5a3c3134ec Move value into common place to be shared across states 2020-08-18 21:25:03 -07:00
John Keiser ce8b9ee8c4 Move finish() out to walk_document 2020-08-18 21:25:03 -07:00
John Keiser 970dfc9f67 builder -> visitor, parser -> iter 2020-08-18 21:25:03 -07:00
John Keiser 04d39c0961 Make tape_builder primary entry point to stage 2 2020-08-18 21:25:01 -07:00
John Keiser d6339aa015 Set is_array in builder 2020-08-18 17:41:48 -07:00
John Keiser 11076bf337 containing_scope -> open_container 2020-08-18 17:41:16 -07:00
Daniel Lemire 8a8eea53a2 Prefixing macros (issue 1035) (#1124)
* Renaming partially done.

* More prefixing.

* I thought that this was fixed.

* Missed one.

* Missed a few.

* Missed another one.

* Minor fixes.
2020-08-18 18:25:36 -04:00
Daniel Lemire 09bd7e8ef8 Verification and fix for issue 1063 (JSON Pointers) (#1064)
* Specification is not followed.

* Fixes.

* Do not pass string_view by reference.

* Better documentation.

* The example is written for exceptions.

* Better documentation.

* Updating with deprecation.

* Updating example.

* Updating example.
2020-08-18 17:23:18 -04:00
John Keiser 9356619380 Merge pull request #1110 from simdjson/jkeiser/number-corruption
Fix potential buffer overrun with heavily customized input and padding
2020-08-18 14:17:25 -07:00
Daniel Lemire fc15147cf5 This allows the users to disable threading. (#1122)
* This allows the users to disable threading.

* This would disable bash scripts under FreeBSD. (#1118)

* This would disable bash scripts under FreeBSD.

* Let us also disable GIT.

* Let us try to just disable GIT

* Nope. We must have both bash and git disabled.

* This allows the users to disable threading.
2020-08-18 16:43:08 -04:00
John Keiser ab6b7a8044 Make last_structural() helper 2020-08-18 10:12:42 -07:00
John Keiser 07c2fe726e Fail if hash is unclosed at start 2020-08-18 10:10:01 -07:00
John Keiser fa355603fb Add test for corruption while parsing a number 2020-08-18 10:10:01 -07:00
Daniel Lemire 109bb505d8 Adding a new test file. (#922)
* Adding a new test file.

* Renaming.
2020-08-18 10:42:45 -04:00
Daniel Lemire 4a6eebc0e4 This corrects a small typo in the documentation. (#1121)
* This corrects a small typo in the documentation.

* Modifying the test as well.
2020-08-18 08:36:15 -04:00
PavelP 78ce2b473e Copy README.md/amalgamate_demo.cpp only if output dir isn't the same as ${SCRIPTPATH} (#1113)
+ use test's `-ef` file operator to check if ${SCRIPTPATH} and ${AMALGAMATE_OUTPUT_PATH} are not the same
2020-08-18 08:35:21 -04:00
Daniel Lemire 6beb5f5587 This adds debug tests in CI. (#1123)
* This adds debug tests in CI.

* Removing silly labels.

* Typo
2020-08-17 13:36:30 -04:00
Daniel Lemire 501fed6c4f This would disable bash scripts under FreeBSD. (#1118)
* This would disable bash scripts under FreeBSD.

* Let us also disable GIT.

* Let us try to just disable GIT

* Nope. We must have both bash and git disabled.
2020-08-17 11:50:57 -04:00
Daniel Lemire b1bd8e9ee2 Update issue templates 2020-08-17 08:16:39 -04:00
Daniel Lemire daeca1bb18 Basics. (#1116) 2020-08-14 17:28:09 -04:00
Daniel Lemire 17f6d5208f Documenting and fixing the case where a string is immediately followed by a scalar (#1106)
* Documenting and fixing.

* More cleaning.

* Being a bit cleaner.
2020-08-14 16:19:57 -04:00
John Keiser bee4d7a12b Merge pull request #1108 from simdjson/jkeiser/ncgdoc
Remove information about nonexistent computed gotos :)
2020-08-12 10:39:20 -07:00
Daniel Lemire f32e3e0c7c Please don't use GNU-specific flags. (#1109) 2020-08-11 09:12:39 -04:00
John Keiser 1b69612246 Remove information about nonexistent computed gotos :) 2020-08-10 16:29:24 -07:00
Daniel Lemire 9e93509a56 Fix number parsing (too lenient). (#1107)
* Fix number parsing (too lenient).

* Minor tweak.

* These are Booleans.

* Tweaking test config
2020-08-10 18:10:11 -04:00
Daniel Lemire ef45cd3342 Let us be explicit about standard compliance (#1099)
* Let us be explicit about standard compliance

* More explicit.
2020-08-06 18:24:36 -04:00
Daniel Lemire 46fe2e6b44 Update README.md 2020-08-06 18:03:10 -04:00
John Keiser 1133c2cc1d Merge pull request #1070 from pps83/bugfix/Do-not-update-README-and-amalgamate_demo
Do not update README.md and amalgamate_demo.cpp from amalgamate.sh
2020-08-06 12:43:56 -07:00
Daniel Lemire fde10553e0 Update HACKING.md 2020-08-06 15:06:31 -04:00
Daniel Lemire 83615ff351 Fixes issue 1088 (#1096) 2020-08-06 11:42:13 -04:00
Pavel P 352eb4cb6d Do not update README.md and amalgamate_demo.cpp from amalgamate.sh
README.md and amalgamate_demo.cpp are always the same, there is no point to keep a copy and recreate them from amalgamate.sh
2020-08-06 09:11:20 +06:00
Daniel Lemire 75c75ac00c This is dead code. (#1095) 2020-08-05 16:48:10 -04:00
John Keiser d9bcf52db2 Merge pull request #1062 from simdjson/jkeiser/reamalgamate
Fix C++ 20 compilation
2020-08-04 21:08:24 -07:00
Daniel Lemire 43f0362e6d Update README.md 2020-08-04 19:44:52 -04:00
John Keiser ed5e313c73 Reamalgamate 2020-08-04 13:17:23 -07:00
John Keiser c0010f60e6 Add view support to simdjson_result<array/object> 2020-08-04 13:17:23 -07:00
John Keiser 75301e4cf5 Fix C++20 compilation 2020-08-04 13:17:23 -07:00
John Keiser 875c8fdcbe Merge pull request #1071 from pps83/quick-example-at-the-top-of-simdjson.h
Add a quick example at the top of simdjson.h
2020-08-04 11:07:21 -07:00
John Keiser a0b1642dc0 Merge pull request #1090 from simdjson/jkeiser/sax
Split stage 2 in SAX fashion
2020-08-04 10:58:59 -07:00
John Keiser 1d7e54f8c9 Merge pull request #1089 from simdjson/jkeiser/stage2misc
Special case empty objects and arrays
2020-08-04 10:57:11 -07:00
Daniel Lemire 77c8581bc0 Flipping the flags 2020-08-04 12:59:23 -04:00
John Keiser 5dd625916b Decrement depth just before checking 2020-08-03 23:09:21 -07:00
John Keiser e3d7718cf3 Simplify value switch statements 2020-08-03 23:09:21 -07:00
John Keiser 9eccd7b1fb Inline start_object/start_array 2020-08-03 23:09:21 -07:00
John Keiser 5b05d126b4 Consolidate start_object calls 2020-08-03 23:09:20 -07:00
John Keiser 03aaf189c1 Use parse_primitive (negative perf!) 2020-08-03 23:09:20 -07:00
John Keiser 6ef9395419 "parser.parser" -> "parser.dom_parser" 2020-08-03 23:09:20 -07:00
John Keiser 3a56e13b78 Make parse() a method 2020-08-03 23:09:19 -07:00
John Keiser ec28acba3d De-templatize stage2::structural_parser 2020-08-03 23:09:15 -07:00
John Keiser ee6647ce40 Make parse part of structural_parser 2020-08-03 17:50:51 -07:00
John Keiser 03d54f8f6e Use SAX model for stage 2 2020-08-03 17:50:51 -07:00
John Keiser 553e6d7549 Don't check max depth on startup 2020-08-03 17:49:14 -07:00
John Keiser e6896ee71e Keep current JSON after checking primitive type 2020-08-03 13:30:13 -07:00
John Keiser e6762f9b48 Advance immediately upon evaluating a character 2020-08-03 13:26:56 -07:00
John Keiser 099bb1afef Pass buffer to primitive parse functions 2020-08-03 12:56:35 -07:00
John Keiser 9c33093c91 Name goto labels consistently 2020-08-03 11:47:38 -07:00
John Keiser 634d8038b9 Increment depth before starting a scope 2020-08-03 11:35:46 -07:00
John Keiser ad46154f2f Hardcode document start/end creation 2020-08-03 10:23:32 -07:00
Daniel Lemire c7fbb4615c Update README.md 2020-08-03 12:51:21 -04:00
John Keiser fa81068ea8 Simplify structural_parser.start() 2020-08-03 09:49:15 -07:00
John Keiser 70c2a1c9f9 Short-circuit empty objects/arrays 2020-08-03 09:36:18 -07:00
Pavel P 164fcb49d9 + reformat sample code 2020-08-03 19:48:41 +06:00
John Keiser 64cf18aa1e Merge pull request #1079 from simdjson/jkeiser/no-error
[3/3] Return errors immediately instead of using goto
2020-08-02 12:22:53 -07:00
John Keiser 66a68ce264 Return errors immediately instead of using goto 2020-08-02 12:04:12 -07:00
John Keiser 86162aaddb Merge pull request #1078 from simdjson/jkeiser/no-computed-goto
[2/3] Remove computed GOTOs
2020-08-02 11:49:35 -07:00
John Keiser 9cc7a94a94 Merge pull request #1065 from simdjson/jkeiser/anonymous-namespace
[1/3] Wrap simdjson kernels in anonymous namespaces
2020-08-02 11:37:11 -07:00
John Keiser 6bca1225e6 Add unlikely in strategic places 2020-08-01 18:19:36 -07:00
John Keiser 379a4e6a01 namespace { -> unnamed namespace 2020-08-01 14:46:23 -07:00
John Keiser 460cfcaf3e Make parse_structurals inline 2020-08-01 14:43:50 -07:00
John Keiser 8e69103822 Remove computed GOTO 2020-08-01 14:43:50 -07:00
John Keiser 2f67dab2b6 Remove extraneous machine addresses 2020-08-01 14:43:50 -07:00
John Keiser bb65ebd8be Remove computed gotos from parse_value 2020-08-01 14:43:50 -07:00
John Keiser c46ea0390c Move { and [ to the start of the switch 2020-08-01 14:43:50 -07:00
John Keiser bc8a6dd2e3 Remove dead code 2020-08-01 14:43:10 -07:00
John Keiser b1478c37f6 Fix arm64 build 2020-08-01 14:43:10 -07:00
John Keiser 4e944a9f3c Eliminate unused functions in fallback 2020-08-01 14:43:10 -07:00
John Keiser c7fa9b5fe8 Make entire implementation namespaces anonymous 2020-08-01 14:43:10 -07:00
John Keiser 65148b123b Put anonymous namespace in front of everything 2020-08-01 14:43:10 -07:00
Daniel Lemire 2f92a34bb7 Turns out that passing dom::element by reference can be a performance killer. (#1086)
* Turns out that passing dom::element by reference can be a performance killer.

* Tweaking.
2020-08-01 10:31:47 -04:00
Daniel Lemire 54ed24f481 Update README.md 2020-07-31 15:47:42 -04:00
Daniel Lemire 268df9f67a Update basics.md 2020-07-31 15:43:34 -04:00
Daniel Lemire 84dc398d32 Adding a couple of tests. 2020-07-31 15:29:10 -04:00
Daniel Lemire f6a3205d10 Avoid allocations in global objects (#1082) 2020-07-30 13:14:56 -04:00
Christoph Reiter 522cb66582 Make MSYS2 CI jobs actually use MSYS2 (#1081)
The jobs were executed in powershell using the globally installed cmake.
This makes things actually run in a MSYS2 shell.

This also removes the msys/cygwin job because it doesn't build
(it complains about undeclared posix_memalign)
2020-07-29 19:34:14 -04:00
Daniel Lemire f873a140ce Tweaking 2020-07-27 16:24:27 -04:00
PavelP 36dfc5bbd1 Add missing strings.h include for non-windows builds (required by strcasecmp) (#1067)
addresses #1066
2020-07-27 16:23:06 -04:00
Daniel Lemire f80668e87f This removes the crazy alignment requirements. (#1073)
* This removes the crazy alignment requirements.
2020-07-27 16:19:01 -04:00
Daniel Lemire dcb5d47ee6 Being clearer. 2020-07-26 15:58:35 -04:00
PavelP e95c22eb21 Add MSYS target for msys2 github workflow (#1075)
* Add MSYS target for msys2 github workflow

* Minimized differences in mingw/mingw64 CI workflows
2020-07-26 15:33:57 -04:00
Daniel Lemire 9fb83e61ea We want the tests to run on PR. 2020-07-26 14:39:47 -04:00
Pavel P 1513cdf7bc Add a quick example at the top of simdjson.h 2020-07-26 14:31:03 -04:00
Daniel Lemire e33af1a3f8 Adding strings.h header. (#1074) 2020-07-25 15:27:19 -04:00
Daniel Lemire 857d77a10a Adding msys2 tests. 2020-07-25 14:32:30 -04:00
PavelP 0e431a0250 Use Unix line endings for c/c++ code (#1069)
This is required for amalgamate.sh to produce correct results
2020-07-25 13:53:31 -04:00
John Keiser 3acfc0b630 Merge pull request #1045 from simdjson/jkeiser/generic-2
Define namespaces inside generic files
2020-07-24 12:42:39 -07:00
Daniel Lemire 2ce5f69def fix recently introduced overflow (#1060)
* Various fixes.

* Clearer comment.
2020-07-24 13:59:24 -04:00
John Keiser 7d347be902 Untangle amalgamated headers 2020-07-24 02:56:41 -07:00
John Keiser a456d78fe0 really_inline more things 2020-07-24 02:56:41 -07:00
John Keiser bf67c967d6 Inline jsoncharutils per-implementation 2020-07-24 02:56:41 -07:00
John Keiser 44b7a7145c Include bitmanip/simd everywhere 2020-07-24 02:56:39 -07:00
John Keiser 3867ee71ed Include files where they are used 2020-07-24 02:56:37 -07:00
John Keiser 464f4813e3 Define namespaces inside generic files 2020-07-24 02:56:36 -07:00
John Keiser af8b52e7e8 Target region for entire compilation of an implementation 2020-07-24 02:48:25 -07:00
Daniel Lemire 796588900c Reenabling C++ 20 features. (#1059) 2020-07-21 18:12:04 -04:00
Daniel Lemire 4beb2ed507 Make simd8 64 uncopyable and other Visual Studio optimizations (#1031)
* Working on making simd8x64 immutable


* Even less invasive
2020-07-21 18:11:21 -04:00
Daniel Lemire 0ff6833e96 Update basics.md 2020-07-21 17:29:10 -04:00
Daniel Lemire e2cfcc52b3 Disabling cxx20 (#1058)
* Disabling C++ 20 features.

* Updating single-header.
2020-07-21 17:15:31 -04:00
Daniel Lemire fc8a46025e Better documentation of default_batch_size (#1056)
* Better documentation of default_batch_size

* Retweaking.
2020-07-21 15:15:21 -04:00
Joe Jevnik d2bea0c228 Add support for C++ 20 ranges. (#1050)
C++ 20 adds a new feature called "ranges", which provides components for dealing
with sequences of values: https://en.cppreference.com/w/cpp/ranges.

A range is like a normal object containing `begin` and `end`, except there are
also composable operations like maps, filters, joins, etc.
The iterator objects returned by a range's `begin` and `end` require a more
strict set of operations than is needed for a range-for loop.

This PR adds the extra operations needed to support turning `dom::array` and
`dom::object` into a range.
This PR does not depend on any C++ 20 behavior, the added operators are all
valid C++ 11, and are already part of the LegacyIterator concepts.
This PR adds extra code behind: `#if defined(__cpp_lib_ranges)` guards, which is
the new C++ 20 specified feature test macro for ranges support. When ranges
support is detected, extra compile time checks are added to ensure that
`dom::array` and `dom::object` satisfy the range concept. No runtime tests have
been added yet because these compile time checks should be sufficient.

If desired, the `static_assert` code could be moved out of the actual code
headers and put into a test file.
2020-07-21 13:27:39 -04:00
Daniel Lemire f016c2b72f Update README.md 2020-07-21 12:02:30 -04:00
Daniel Lemire be62058696 Adds some C++20 tests (only headers). (#1053)
* Adds some C++20 tests (only headers).

* Tweaking.
2020-07-21 10:37:52 -04:00
Daniel Lemire af18d5ed81 This adds a validation benchmark (#1040) 2020-07-20 18:56:39 -04:00
Daniel Lemire e9c91a1ce2 lookup4 (new UTF-8 validation) (#993)
* lookup4

* Self-document lookup4 and clean up extra bits

* Maintenance, to match against upcoming PR.

Co-authored-by: Daniel Lemire <lemire@gmai.com>
Co-authored-by: John Keiser <john@johnkeiser.com>
2020-07-20 18:20:07 -04:00
Daniel Lemire 29767b2886 Moving gcc 7 out of circle ci (#1052) 2020-07-20 17:49:55 -04:00
Daniel Lemire 96a31c69c5 Update README.md 2020-07-17 15:41:54 -04:00
Daniel Lemire 534632dc52 Minor tweak on number parsing (#1041)
* Tweak.
2020-07-17 12:14:10 -04:00
Daniel Lemire 8bf5f3d869 Trying to document more carefully the use of memcpy. (#1038)
* Trying to document more carefully the use of memcpy.

* Patching spelling.
2020-07-17 09:58:34 -04:00
Daniel Lemire c4f92322f5 Update README.md 2020-07-17 09:27:19 -04:00
Vitaly Baranov 1e4aa116e5 Choose active implementation only once. (#1044) 2020-07-16 18:17:56 -04:00
John Keiser 90cc1411da Merge pull request #1018 from simdjson/jkeiser/simplify-integer-parse
Remove some branches from number parsing
2020-07-16 12:21:43 -07:00
Daniel Lemire d13ce6768c Update README.md 2020-07-16 13:05:28 -04:00
gerrymanoim fd4a7f2150 DOC: Add another python binding to README (#1043) 2020-07-16 13:04:18 -04:00
Vitaly Baranov 6bd64c6873 Fix clang warning -Wused-but-marked-unused. (#1042)
* Fix clang warning -Wused-but-marked-unused.

* Fix build.
2020-07-15 13:28:51 -04:00
Daniel Lemire ba58d868e5 Update performance.md 2020-07-14 15:00:31 -04:00
Ben McMorran c50799ba3b Fix TOC links in basics documentation
The "++" in "C++" gets stripped from the generated anchors, so the links in the table of contents didn't work.
2020-07-13 17:02:35 -04:00
Daniel Lemire 039d82ff1b Returning basictests to its original function: basic tests (only) (#1010)
* The initial motivation behind basictests was for a quick set of sanity tests to check whether your code made sense. It
was not meant for thorough testing to find corner cases. However, over time, it grew to include such expensive tests.
This PR takes them out. It also allows us to bring back basictests to MinGW tests, since it is now cheap.

This is not an exercise in software engineering and making things prettier. This is a pragmatic change to improve our
test coverage and quality of life.

* Adds many more cheap tests.

Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-07-13 09:39:35 -04:00
Vitaly Baranov a2f0933d01 Fix undefined behavior: load of misaligned address in atomparsing.h (#1037) 2020-07-13 08:46:52 -04:00
Daniel Lemire 77e1e3cc18 Update performance.md 2020-07-12 18:35:15 -04:00
Daniel Lemire 7bdd41350a Update performance.md 2020-07-12 18:31:45 -04:00
John Keiser 6797a6ab56 Use const uint8_t * in number parsing 2020-07-10 09:17:23 -07:00
John Keiser 86b5928f5e Use parse_digit for decimal and exp parsing as well 2020-07-10 09:16:43 -07:00
John Keiser 6dbd15aa71 Move SIMDJSON_SKIPNUMBERPARSING method out 2020-07-09 15:55:10 -07:00
John Keiser 22e5b081c4 Remove is_integer 2020-07-09 15:55:10 -07:00
John Keiser d848f33c48 Simplify integer parsing 2020-07-09 15:55:10 -07:00
John Keiser c64367536d Eliminate "found_minus" parse_number() parameter 2020-07-09 15:55:09 -07:00
John Keiser fc0102b079 Use common parse_digit() funtion in int parsing 2020-07-09 15:33:22 -07:00
Daniel Lemire 62a39639c2 Update performance.md 2020-07-09 11:47:33 -04:00
Daniel Lemire 158aaff384 Update performance.md 2020-07-09 11:46:35 -04:00
Daniel Lemire fd836145fe Update performance.md 2020-07-09 11:45:47 -04:00
Daniel Lemire 697bafdd0a Update performance.md 2020-07-08 08:32:41 -04:00
Daniel Lemire 9675dcac44 Update performance.md 2020-07-06 19:03:18 -04:00
Daniel Lemire 48849d7866 Update README.md 2020-07-06 18:59:45 -04:00
Daniel Lemire d0ce2f0b5a Fixing clang under visual studio (#1028)
* Lots of fixes

* Removing some lambdas

* Removing some functional programming.

Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-07-06 18:58:19 -04:00
Daniel Lemire a19f635a6a clang is busted under appveyor (#1029)
Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-07-06 18:28:23 -04:00
Daniel Lemire 676ed59342 Adding more github actions (#1027)
* Adding more github actions


Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-07-06 18:20:06 -04:00
Daniel Lemire 4015f46b7d Adding a new flag to tell Visual Studio to include debugging information (#1026)
in the release builds. This makes it easier to profile inside Intel
VTune when needed.
2020-07-06 17:53:57 -04:00
Daniel Lemire 770cee7139 Fail when we "force inline" and visual studio bypasses us. (#1025) 2020-07-06 17:53:32 -04:00
Daniel Lemire a4619a54a7 Update README.md 2020-07-04 11:53:53 -04:00
Daniel Lemire f7d99f97a3 Update performance.md 2020-07-04 11:52:40 -04:00
Daniel Lemire 8b7df0c12e Update performance.md 2020-07-03 23:14:01 -04:00
Daniel Lemire bd780817f7 Update performance.md 2020-07-02 15:33:36 -04:00
John Keiser 82fb45aa2a Merge pull request #990 from simdjson/jkeiser/fast-large-integer
Don't reparse large integers
2020-07-01 12:49:43 -07:00
Daniel Lemire 74870a8189 Fixing issue 1013. (#1016)
* Fixing issue 1013.

* Bumping to 0.4.6

Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-07-01 14:14:51 -04:00
John Keiser 7a9f6b48f4 Replace TODOs with comments about why we DIDNTDO 2020-07-01 10:31:10 -07:00
John Keiser d3c089130d Check overflow without reparsing integers 2020-07-01 09:51:48 -07:00
John Keiser e0f3060527 Add negative/positive integer writing 2020-07-01 09:51:48 -07:00
John Keiser 4c1256acc4 Reduce nesting somewhat with different if() order 2020-07-01 09:51:48 -07:00
John Keiser 85f6f5bd29 Use macros to remove #ifdefs on every write 2020-07-01 09:51:48 -07:00
John Keiser 4d9eac663a Use a macro to get rid of #ifdefs on each invalid number check 2020-07-01 09:51:48 -07:00
Daniel Lemire 0ef4d90ad0 Fix for issue 1014. (#1015)
* Fix for issue 1014.

* Explanation.

Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-30 19:36:26 -04:00
Daniel Lemire 1a1e7edb02 Tweaking the recently introduced mingw tests. (#1011)
Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-30 12:47:44 -04:00
Daniel Lemire 51b835f71b Correcting typo (#1007)
Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-30 10:19:37 -04:00
Daniel Lemire e38fe3d361 Version update 2020-06-30 09:41:20 -04:00
myd7349 cc042c9936 CMAKE_VS_PLATFORM_TOOLSET might be empty (#1009)
According to https://gitlab.kitware.com/cmake/cmake/-/issues/17976,
CMAKE_VS_PLATFORM_TOOLSET is set only when using a Visual Studio generator.

When we use Ninja as the generator, CMAKE_VS_PLATFORM_TOOLSET will be empty.
As a result:
if(${CMAKE_VS_PLATFORM_TOOLSET} STREQUAL "v140")
will be treated as:
if( STREQUAL "v140")

We may also quote it like this:
if("${CMAKE_VS_PLATFORM_TOOLSET}" STREQUAL "v140")
but that won't make the warnings disappeared in VS2015.
2020-06-30 09:40:19 -04:00
Daniel Lemire 599e3bc937 Update README.md 2020-06-29 21:52:08 -04:00
Daniel Lemire 1fa0d940bc Update README.md 2020-06-29 21:44:05 -04:00
Daniel Lemire 7dc4a9525b Update README.md 2020-06-29 21:43:07 -04:00
Daniel Lemire b6f1f4ef64 Update basics.md 2020-06-29 21:41:50 -04:00
Daniel Lemire 3faae67663 New release 2020-06-29 21:11:58 -04:00
Daniel Lemire ccc94c9b05 Mingw tests (32-bit and 64-bit) (#1004) 2020-06-29 21:10:54 -04:00
Daniel Lemire 1fd30db726 This example in our documentation would not compile (#1005)
Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-29 16:25:11 -04:00
Daniel Lemire 0ba76ac066 This enables building the library under Visual Studio 2015 (#1002)
Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-29 08:43:47 -04:00
Daniel Lemire 8b661fe556 Merge pull request #1001 from simdjson/dlemire/justlib_install
We do not properly test just library.
2020-06-28 13:12:42 -04:00
Daniel Lemire 077907b7c3 Preparing a new patch release. 2020-06-28 12:40:13 -04:00
Daniel Lemire 172d669780 We do not properly test just library. 2020-06-28 12:25:17 -04:00
Daniel Lemire 6b85b9a416 Merge pull request #998 from simdjson/issue976
Final steps.
2020-06-26 21:05:06 -04:00
Daniel Lemire 5d3001279c Update CONTRIBUTORS 2020-06-26 20:36:19 -04:00
Daniel Lemire 4582a13360 Final steps. 2020-06-26 20:31:24 -04:00
Daniel Lemire 3a064535ae Merge pull request #994 from simdjson/issue976
Fix for issue 976 (something like 32-bit support)
2020-06-26 20:02:15 -04:00
Daniel Lemire 444ec4ad27 Stupid me 2020-06-26 19:29:28 -04:00
Daniel Lemire 94e910586d Removing a cast. 2020-06-26 19:06:39 -04:00
Daniel Lemire bb5ce007e6 Something better. 2020-06-26 19:03:28 -04:00
Daniel Lemire deaa74d378 Re-enabling tests generally. 2020-06-26 18:57:34 -04:00
Daniel Lemire 13e1794e91 Merge pull request #995 from simdjson/dlemire/issue988
This introduces a new option to forcefully disable threads for people who also want them enabled
2020-06-26 18:37:18 -04:00
Daniel Lemire 67b3595008 Making it clear that it may disappear. 2020-06-26 13:29:50 -04:00
Daniel Lemire 6c33f518a8 This introduces a new option to forcefully disable threads. 2020-06-26 13:23:44 -04:00
Daniel Lemire 88da62ba09 Better documentation in the code. 2020-06-26 13:02:12 -04:00
Daniel Lemire b6997a56df Patching things up and adding tests. 2020-06-26 12:15:16 -04:00
Daniel Lemire 74178fd1c2 Merge pull request #991 from knapply/master
Permit 32-bit GCC compilation
2020-06-26 09:50:18 -04:00
Brendan Knapp 34c59bfa90 Merge pull request #1 from CountOnes/master
Minor fixes to avoid 32-bit warnings.
2020-06-25 18:43:40 -07:00
Daniel Lemire 2956bce047 Minor fixes to avoid 32-bit warnings. 2020-06-25 21:12:26 -04:00
Brendan Knapp 41f33ecbb9 Permit 32-bit GCC compilation 2020-06-25 17:07:17 -07:00
Daniel Lemire 86241e2871 Merge pull request #987 from simdjson/issue985
Removing optional since it is not C++11, and it is not used
2020-06-25 11:04:36 -04:00
Daniel Lemire 1e32897d3e Merge pull request #986 from simdjson/issue984
Fixing issue 984
2020-06-25 11:04:19 -04:00
Daniel Lemire 1b63a9a9b5 Removing optional since it is not C++11 2020-06-25 10:25:57 -04:00
Daniel Lemire 4c9f11b78a Missing character. 2020-06-25 10:15:13 -04:00
Daniel Lemire 32348c2b0b Elaborating. 2020-06-25 10:14:29 -04:00
Daniel Lemire 5e690c5d04 Fixing the string_view issue. 2020-06-25 10:02:10 -04:00
Daniel Lemire 4ec56484a1 Merge pull request #979 from simdjson/issue977
This removes git as a dependency to our CMake
2020-06-24 20:45:15 -04:00
Daniel Lemire 8f2a5649fe Merge pull request #983 from TkTech/patch-1
Fix documentation links in basics.md
2020-06-24 20:44:46 -04:00
Daniel Lemire c3b25e12a5 Update implementation-selection.md 2020-06-24 20:42:04 -04:00
Daniel Lemire 6d3e33d440 Update parse_many.md 2020-06-24 20:41:38 -04:00
Daniel Lemire c11f7ce54f Update performance.md 2020-06-24 20:41:06 -04:00
Tyler Kennedy 84806cc174 Fix documentation links in basics.md
Links to other files need to be either relative to themselves (doc/performance.md -> performance.md) or absolute (doc/performance.md -> /doc/performance.md). This change fixes the documentation when read on GitHub.
2020-06-24 20:20:14 -04:00
Daniel Lemire 16f12f7d59 Tweak. 2020-06-24 19:31:51 -04:00
Daniel Lemire 8609b8e589 Adding a ninja test. 2020-06-24 19:29:08 -04:00
Daniel Lemire 29e744fdbb Adding warning message. 2020-06-24 19:23:02 -04:00
Daniel Lemire 515b87bcbe Disabling perfcheck for ninja 2020-06-24 18:45:47 -04:00
Daniel Lemire 5fa9faca20 Merge pull request #980 from simdjson/dlemire/put_back_perf_tests
Putting back the perf tests.
2020-06-24 17:19:24 -04:00
Daniel Lemire a4ebdfd47c Merge pull request #975 from simdjson/dlemire/nitpicking_amal_demo
Nitpicking: demo should not crash on missing input
2020-06-24 17:18:40 -04:00
Daniel Lemire 188d8d4b64 More verbose. 2020-06-24 17:09:18 -04:00
Daniel Lemire ce5581d428 This makes it so that if we are under someone else, we just build the library. 2020-06-24 17:00:19 -04:00
Daniel Lemire 5b4acf14ea Removing space. 2020-06-24 16:51:28 -04:00
Daniel Lemire 5fc6cb15b8 This should make things even more robust. If .git is not found, just disable all git work. 2020-06-24 16:12:19 -04:00
Daniel Lemire f6e9a8eee4 Making the cmake more verbose so we can figure out what is happening. 2020-06-24 15:44:22 -04:00
Daniel Lemire 6c0950cb2e Putting back the perf tests. 2020-06-24 15:28:28 -04:00
Daniel Lemire cb8a9ef2c0 This removes git as a dependency 2020-06-24 15:13:47 -04:00
Daniel Lemire 470cbbe9ff Nitpicking. 2020-06-23 22:07:40 -04:00
Daniel Lemire e01f1434fb Bumping up the version number 2020-06-23 20:55:52 -04:00
John Keiser 187084ce46 Merge pull request #970 from simdjson/jkeiser/singleheader-tests
Make singleheader tests be test-only
2020-06-23 17:07:03 -07:00
John Keiser b6f9382b5b Merge pull request #972 from simdjson/jkeiser/effc++
Compile with -Weffc++ in CI
2020-06-23 17:06:35 -07:00
Daniel Lemire 57f68381ed Merge pull request #973 from simdjson/dlemire/testing_static_lib
Because we are dynamic by default, we never test static!
2020-06-23 19:50:49 -04:00
Daniel Lemire 3e35729eb6 Merge pull request #968 from simdjson/issue961
Fixing issue 961
2020-06-23 19:48:43 -04:00
Daniel Lemire 544fa57641 Damn merge conflicts. 2020-06-23 19:15:47 -04:00
Daniel Lemire 7e94309046 Update basics.md 2020-06-23 19:08:14 -04:00
Daniel Lemire 21eff5b825 Introducing some variety. 2020-06-23 18:58:38 -04:00
Daniel Lemire b408d7c95e Because we are dynamic by default, we never test static! 2020-06-23 18:40:57 -04:00
John Keiser d9929edbc1 Run -Weffc++ in CI 2020-06-23 13:44:25 -07:00
John Keiser 843b73dedb Make singleheader tests be test-only 2020-06-23 13:35:27 -07:00
John Keiser 02a8145b18 Merge pull request #962 from simdjson/jkeiser/issue953
Fix #953: simdjson.cpp fails -Wall compiled on its own
2020-06-23 13:30:04 -07:00
Daniel Lemire cfcb315b14 Merge pull request #967 from simdjson/dlemire/improving_documentation
This improves slightly the documentation, adding instructions for CMake users.
2020-06-23 15:49:42 -04:00
Daniel Lemire c8a70a0a73 Tweaking the documentation. 2020-06-23 14:39:16 -04:00
Daniel Lemire b84a3a0230 Merge branch 'master' into issue961 2020-06-23 14:33:06 -04:00
Daniel Lemire 49d70232f8 Merge pull request #969 from simdjson/dlemire/minor_pre0.4_cleaning
Very minor cleaning.
2020-06-23 14:30:47 -04:00
Daniel Lemire 8cc9f496ee Merge branch 'master' into dlemire/improving_documentation 2020-06-23 13:07:29 -04:00
Daniel Lemire 1547f2ec80 Pleasing John 2020-06-23 13:05:19 -04:00
John Keiser 42a8b40de0 Reamalgamate 2020-06-23 09:53:36 -07:00
John Keiser b4b968ff44 Fix #953 2020-06-23 09:53:24 -07:00
John Keiser 52e3c063c5 Add repro for #953
Depend on singleheader-files via custom target to avoid races
2020-06-23 09:53:21 -07:00
John Keiser 257089884f Merge pull request #958 from simdjson/jkeiser/is
Make simdjson_result<element>.is() return bool
2020-06-23 09:51:37 -07:00
John Keiser c650ea9765 Merge pull request #960 from simdjson/jkeiser/idiomatic-get
Convert simdjson to use .get()
2020-06-23 09:49:41 -07:00
John Keiser e369d45b9c Fix non-compileable examples 2020-06-23 09:48:17 -07:00
John Keiser 2d84b6f6d9 Make simdjson_result<element>.is() return bool 2020-06-23 09:09:24 -07:00
John Keiser eef1171944 Merge pull request #954 from simdjson/jkeiser/parse-many-result
Return error from parse_many
2020-06-23 09:06:20 -07:00
John Keiser 12ccdcf858 Include document_stream line in parse_many docs 2020-06-23 08:49:47 -07:00
Daniel Lemire f1a03bfb04 Very minor cleaning. 2020-06-23 11:05:58 -04:00
Daniel Lemire 696b0e29e4 Fixing issue 961 2020-06-23 10:47:32 -04:00
Daniel Lemire 5eb748ae17 This improves slightly the documentation, adding instructions for CMake users. 2020-06-23 09:33:15 -04:00
Daniel Lemire aa4340ef5c Merge pull request #957 from simdjson/dlemire/install_just_lib
This might enable folks to just build the library.
2020-06-23 09:12:28 -04:00
Daniel Lemire 0062e54e93 Merge pull request #959 from simdjson/dlemire/utf8_val
Expose the UTF-8 string validation functions
2020-06-22 21:34:02 -04:00
Daniel Lemire dada5090b0 These compilers are insane. 2020-06-22 20:25:55 -04:00
Daniel Lemire 1c4593c648 These compilers are really pedantic. 2020-06-22 20:04:37 -04:00
Daniel Lemire e7004cef76 Removing a test so that it is all ASCII. 2020-06-22 16:55:16 -04:00
Daniel Lemire 2bb101bd19 Code reformatting. 2020-06-22 16:50:57 -04:00
Daniel Lemire 26baf70912 Pedantic compiler 2020-06-22 16:45:32 -04:00
Daniel Lemire 89c2582376 Extending the documentation. 2020-06-22 16:32:00 -04:00
Daniel Lemire 33e003616d Fixing the name of the variable 2020-06-22 16:29:38 -04:00
Daniel Lemire bf03d77ab9 Passing by value the string_view 2020-06-22 16:28:35 -04:00
Daniel Lemire a6cbf1f922 Going generic... 2020-06-22 16:25:11 -04:00
Daniel Lemire d6f056f266 Fixing documentation issues. 2020-06-22 16:17:11 -04:00
Daniel Lemire 69a247d500 Adding tests. 2020-06-22 16:12:37 -04:00
Daniel Lemire a76c67c19f Fixing... 2020-06-22 15:57:54 -04:00
Daniel Lemire b836164a38 Fix. 2020-06-22 02:12:49 +00:00
Daniel Lemire 058507badf Putting back the loop 2020-06-21 21:21:49 -04:00
Daniel Lemire ad40e90790 Patching. 2020-06-21 20:14:00 -04:00
John Keiser 0c9dc11550 Use really_inline to help g++ detect initialized variable 2020-06-21 16:27:05 -07:00
John Keiser 1ff55c2729 Replace auto [x,error] with .get() everywhere 2020-06-21 16:26:59 -07:00
Daniel Lemire 066269153e Explaining decision. 2020-06-21 18:02:34 -04:00
Daniel Lemire 38bb08778a With an example. 2020-06-21 17:57:22 -04:00
Daniel Lemire 5dbcdf1484 Ok 2020-06-21 17:52:30 -04:00
Daniel Lemire f03a6ab5a4 Tweaking. 2020-06-21 17:39:24 -04:00
John Keiser 6fa5abcd7e Replace x.get<T>() with x.get(v) or T(x) 2020-06-21 14:36:38 -07:00
Daniel Lemire 5dc07ed295 It builds. 2020-06-21 17:20:33 -04:00
Daniel Lemire 064d4255d5 Ok. 2020-06-21 17:09:06 -04:00
Daniel Lemire 04139eb82e Ok. 2020-06-21 17:05:55 -04:00
John Keiser 1b1a122b1f Fix copy constructor issue on older gcc 2020-06-21 12:06:14 -07:00
Daniel Lemire ccb132320c Merge branch 'dlemire/install_just_lib' of github.com:lemire/simdjson into dlemire/install_just_lib 2020-06-21 14:40:55 -04:00
Daniel Lemire c0e7f824df Enabling the tests. 2020-06-21 14:40:38 -04:00
Daniel Lemire 05bba71eaf Update simdjson-flags.cmake 2020-06-21 14:28:51 -04:00
Daniel Lemire 7ebe5c4bcf This might enable folks to just build the library. 2020-06-21 14:20:58 -04:00
John Keiser ae1bd891e7 Remove deprecated uses of parse_many 2020-06-21 11:19:06 -07:00
John Keiser 9899e5021d Allow use of document_stream with tie() 2020-06-20 21:15:05 -07:00
John Keiser 94440e0170 Return simdjson_result from load_many/parse_many 2020-06-20 20:51:53 -07:00
John Keiser c25928e44f Merge pull request #950 from simdjson/jkeiser/tie-type
replace get<T>.tie(v,e) with get(v)
2020-06-20 20:50:56 -07:00
John Keiser a7fc7d4ffb Switch from get(v,e) to e = get(v) 2020-06-20 17:57:09 -07:00
John Keiser f336103f63 Convert tools/docs/benchmarks to bool get() idiom 2020-06-20 17:55:46 -07:00
John Keiser 56e2b38048 Add bool result from tie()/get(), get<T>(T&,error_code&) 2020-06-20 17:55:46 -07:00
John Keiser a5ccff720a Merge pull request #949 from simdjson/jkeiser/get-type
Add non-template get_xxx/is_xxx methods to element
2020-06-20 17:35:27 -07:00
John Keiser 1d8c2d6c22 Make get_xxx the primary functions 2020-06-20 13:29:12 -07:00
John Keiser 0b8c357eff Add get_X and is_X methods 2020-06-19 13:27:33 -07:00
John Keiser efc168f473 Make test changes only 2020-06-19 13:27:33 -07:00
John Keiser d8428f98d9 Add cast_tester.h 2020-06-19 13:27:33 -07:00
John Keiser 60f17d26a3 Move test macros to a header 2020-06-19 13:27:00 -07:00
John Keiser 05bc664c11 Don't extend from tape_ref in public classes 2020-06-19 13:25:52 -07:00
Daniel Lemire 2cc84b6e51 Merge pull request #943 from simdjson/dlemire/fewer_perf_tests
Fewer performance tests.
2020-06-18 22:04:50 -04:00
Daniel Lemire 5ccdbef7d5 Merge pull request #936 from simdjson/dlemire/new_examples
New examples.
2020-06-18 18:29:06 -04:00
Daniel Lemire c13c2650a2 Merge pull request #940 from simdjson/issue938
Verifying (and fixing) issue 938
2020-06-18 18:25:31 -04:00
Daniel Lemire ec6c998a3a Merge pull request #942 from simdjson/dlemire/better_doxygen_home_page
Tweaks doxygen so that we have a better main page.
2020-06-18 18:25:04 -04:00
Daniel Lemire 2f6091419f Merge pull request #944 from simdjson/issue680
Document the complexity of array.at
2020-06-18 18:24:08 -04:00
Daniel Lemire 2022dd7d74 Merge pull request #945 from simdjson/issue678
Fixing issue 678
2020-06-18 18:23:56 -04:00
Daniel Lemire b8202dab3b Merge pull request #946 from simdjson/issue937
Fixing issue 937
2020-06-18 18:20:44 -04:00
Daniel Lemire ef688a74fe Minor tweak to the documentation. 2020-06-18 18:18:12 -04:00
John Keiser f632e7c043 Put C++11 capable version back, change name to readme style 2020-06-18 12:50:49 -07:00
Daniel Lemire 04a19f9813 Fixes https://github.com/simdjson/simdjson/issues/937 2020-06-17 18:06:13 -04:00
Daniel Lemire 2cbc591c9d Fixing issue 678 2020-06-17 16:17:17 -04:00
Daniel Lemire 3f00e79bcb Merge branch 'master' into dlemire/better_doxygen_home_page 2020-06-17 16:02:49 -04:00
Daniel Lemire 3586fc4910 Fix for issue 680 2020-06-17 18:49:22 +00:00
Daniel Lemire c9a6bbeb64 Merge pull request #935 from simdjson/dlemire/tuning_the_documentation
Some tweaks to the documentation
2020-06-17 14:33:23 -04:00
Daniel Lemire 0655a135e6 Reverting. 2020-06-17 17:52:07 +00:00
Daniel Lemire d3e8bb1889 Fewer performance tests. 2020-06-17 17:44:28 +00:00
Daniel Lemire 14ceacac73 Tweaking. 2020-06-17 13:27:17 -04:00
Daniel Lemire e4f33b5970 Tweaking the message. 2020-06-17 12:36:36 -04:00
Daniel Lemire 4474f8ef18 Cleaning a bit the examples. 2020-06-17 16:24:55 +00:00
John Keiser 76c9f4f5a6 Merge pull request #941 from simdjson/jkeiser/forgot
Remove unnecessary functions
2020-06-17 09:09:28 -07:00
Daniel Lemire 942ef3b7f2 Merge pull request #939 from simdjson/dlemire/lookup3
Introducing lookup3 (UTF-8 validation).
2020-06-17 11:19:09 -04:00
Daniel Lemire 0b9df6d8c4 It turns out that we need fairly complicated logic. 2020-06-17 15:17:10 +00:00
Daniel Lemire b5ea504ad2 Tweaks doxygen so that we have a better main page. 2020-06-17 11:07:21 -04:00
Daniel Lemire 803b0c4bdb Light touch. 2020-06-17 11:00:13 -04:00
Daniel Lemire 6537d0dc76 Avoiding the unused errors. 2020-06-17 14:19:58 +00:00
John Keiser f8f36c085c Remove unnecessary functions 2020-06-17 07:11:53 -07:00
John Keiser 7339f67dd7 Merge pull request #462 from simdjson/jkeiser/if-backslash
Wrap backslash processing in a branch
2020-06-17 07:07:58 -07:00
Daniel Lemire 0d4e501239 Fixing the bug. 2020-06-17 10:06:16 -04:00
Daniel Lemire 8d609607e2 Verifying the bug. 2020-06-16 20:04:09 -04:00
Daniel Lemire 71a889ed73 Introducing lookup3 (UTF-8 validation). 2020-06-16 19:08:25 -04:00
Daniel Lemire 27a75a9085 Tweaking. 2020-06-15 17:54:34 -04:00
Daniel Lemire 954d6c326d New examples. 2020-06-15 17:45:15 -04:00
Daniel Lemire 7ea05d038e New API traversal tests. (#931)
Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-15 13:15:52 -04:00
Daniel Lemire 33930ff046 Adding link. 2020-06-15 13:07:53 -04:00
Daniel Lemire 16f41ea059 Added a word. 2020-06-14 18:48:42 -04:00
Daniel Lemire 0a7270fc29 More tweaks. 2020-06-14 18:47:22 -04:00
Daniel Lemire 23fbd9d004 Some tweaks. 2020-06-14 18:28:09 -04:00
John Keiser 610c79fbf3 Don't use backslash branch on ARM 2020-06-13 07:51:28 -07:00
John Keiser fd44c2a2ff Merge pull request #927 from simdjson/dlemire/exposingthestringminifier
Exposing the string minifier.
2020-06-13 07:47:20 -07:00
John Keiser a86a82b39c Rename minify class to minifier so the minify() method is cleared up 2020-06-12 17:05:25 -07:00
Daniel Lemire 89b059b1ea Testing with GCC 10 and clang 10 (#926)
* Testing with GCC 10 and clang 10

* Fixing spurious space

* gcc10 does not need the cmake installation.

* We don't want to run the perf test on ARM. I ignore them systematically. ARM performance
should be assessed manually.

* Switching to GCC 10 and Clang 10

* Disabling some tests under sanitizers when they involve rapidjson or other parsers.

Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-12 17:58:53 -04:00
Daniel Lemire bd2d0f769f One unlikely too many (#930) 2020-06-12 17:58:10 -04:00
Daniel Lemire d830422489 Put back the amalgamation files and add tests (#929)
Co-authored-by: John Keiser <john@johnkeiser.com>
Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-12 17:57:45 -04:00
Daniel Lemire d1a54249e7 New API traversal tests. 2020-06-12 17:42:57 -04:00
Daniel Lemire 4dfbf98e4e Using a worker instead of a thread per batch (#920)
In the parse_many function, we have one thread doing the stage 1, while the main thread does stage 2. So if stage 1 and stage 2 take half the time, the parse_many could run at twice the speed. It is unlikely to do so. Still, we see benefits of about 40% due to threading.

To achieve this interleaving, we load the data in batches (blocks) of some size. In the current code (master), we create a new thread for each batch. Thread creation is expensive so our approach only works over sizeable batches. This PR improves things and makes parse_many faster when using small batches.

  This fixes our parse_stream benchmark which is just busted.
  This replaces the one-thread per batch routine by a worker object that reuses the same thread. In benchmarks, this allows us to get the same maximal speed, but with smaller processing blocks. It does not help much with larger blocks because the cost of the thread create gets amortized efficiently.
This PR makes parse_many beneficial over small datasets. It also makes us less dependent on the thread creation time.

Unfortunately, it is going to be difficult to say anything definitive in general. The cost of creating a thread varies widely depending on the OS. On some systems, it might be cheap, in others very expensive. It should be expected that the new code will depend less drastically on the performances of the underlying system, since we create juste one thread.

Co-authored-by: John Keiser <john@johnkeiser.com>
Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-12 16:51:18 -04:00
Daniel Lemire 1b6258ec8c Added std::minify 2020-06-12 16:37:41 -04:00
Daniel Lemire be707dbb6f Added a remark 2020-06-12 16:07:34 -04:00
John Keiser 664b03bb13 Short circuit find escapes if there is a backslash 2020-06-12 10:10:35 -07:00
John Keiser 7c6723d912 Print progress bar even if there is only one file 2020-06-12 10:01:19 -07:00
John Keiser 1febf2ec83 Merge pull request #919 from simdjson/jkeiser/move-current-loc
[4/4] Stop persisting current_loc (+2% parse throughput)
2020-06-12 09:55:04 -07:00
John Keiser fe69928764 Merge pull request #918 from simdjson/jkeiser/remove-iterator-variables
[3/4] Remove unneeded structural_iterator variables
2020-06-12 09:52:35 -07:00
John Keiser bbd61eb13f Let tape writing be put in a register 2020-06-12 09:18:20 -07:00
John Keiser e15e1e253d peek_char -> peek_next_char 2020-06-12 09:10:16 -07:00
Daniel Lemire 45e2178ada Duh. 2020-06-11 17:20:28 +00:00
Daniel Lemire a6e4933d93 Exposing the string minifier. 2020-06-11 13:07:18 -04:00
Daniel Lemire 98599e0972 Remove the circleci badge since it may appear to fail due to perfdiff 2020-06-11 11:37:53 -04:00
John Keiser b4837f2e2f Merge pull request #915 from simdjson/jkeiser/stage2-common
[2/4] Use same state machine for stage 2 streaming and non-streaming
2020-06-10 08:37:08 -07:00
John Keiser ea08e7d192 Remove unused extra copy of find_next_document_index 2020-06-09 17:52:13 -07:00
John Keiser d178e089a6 Stop caching current structural, keep current index around instead of
next
2020-06-08 15:21:54 -07:00
John Keiser 5f00b37e21 Stop caching the buffer index 2020-06-08 15:21:54 -07:00
John Keiser 8a8792d47f Remove most uses of current_char() 2020-06-08 15:21:54 -07:00
John Keiser 59d9bc9e48 Store the pointer to the next structural instead of base
structural_indexes and an index
2020-06-08 15:21:54 -07:00
John Keiser 8793dd3ceb Don't store len locally 2020-06-08 15:21:54 -07:00
John Keiser 48062380fa Move parser to structural_iterator 2020-06-08 15:21:54 -07:00
John Keiser 3636aa5522 Extend structural_parser from structural_iterator 2020-06-08 15:21:54 -07:00
John Keiser a1aea4588f Move document stream state to implementation 2020-06-08 15:21:54 -07:00
John Keiser 1d4fffb799 Fix fallback implementation 2020-06-08 15:21:52 -07:00
John Keiser 6f90f5dc5f Remove templating from finish() method 2020-06-08 15:20:56 -07:00
John Keiser 9dd6972d26 Remove impossible checks, add EMPTY check to normal parser 2020-06-08 15:20:56 -07:00
John Keiser d731a7d52c Privatize structural_parser 2020-06-08 15:20:56 -07:00
John Keiser 059468b74e Eliminate streaming_structural_parser subclass with templates 2020-06-08 15:20:56 -07:00
John Keiser 5e69fb782a Call a function to parse structurals 2020-06-08 15:20:56 -07:00
John Keiser a5beffda78 Remove streaming_structural_parser.h 2020-06-08 15:20:56 -07:00
John Keiser 7de7ce5fdc Move document stream state to implementation 2020-06-08 15:20:56 -07:00
John Keiser 383e8c7f68 Merge pull request #913 from simdjson/jkeiser/internal-streaming
[1/4] Simplify parse_many() and fix bugs
2020-06-08 15:19:27 -07:00
John Keiser 0dbda65e44 Fix fallback implementation 2020-06-08 14:52:23 -07:00
John Keiser fe01da077e Make threaded version work again 2020-06-07 16:21:00 -07:00
John Keiser d43a4e9df9 Remove SUCCESS_AND_HAS_MORE (internal only value) 2020-06-07 16:20:55 -07:00
John Keiser 3e226795f0 Run all passing json against parse_many. Empty documents pass, too. 2020-06-07 16:20:51 -07:00
John Keiser c4a0fe1606 Add tests for parse_many() errors 2020-06-07 16:20:46 -07:00
John Keiser ef63a84a3e Move document stream state to implementation 2020-06-07 16:20:44 -07:00
John Keiser 8c16ba372e Acknowledge that we always have a remainder 2020-06-06 16:46:38 -07:00
John Keiser 9be4a17687 Separate definition from declaration, arrange top down 2020-06-06 16:46:38 -07:00
Furkan 89332e1696 Temporary fix to #914 (#917) 2020-06-05 21:01:41 -04:00
John Keiser 8a56129def Merge pull request #916 from simdjson/jkeiser/issue906stage2
Move unclosed array check to stage 2
2020-06-05 14:23:44 -07:00
John Keiser ed0c815735 Move unclosed array check to stage 2 2020-06-05 12:39:13 -07:00
Daniel Lemire 7a69da16e4 Fixing issue 906 (#912)
* Fixing issue 906

* Safe patching.

* Now with explanations.

* Bumping up memory allocation.

* Putting the patch back.

* fallback fixes.

Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-05 15:37:09 -04:00
Daniel Lemire 351717414d updating docker with instructions... (#901)
* Better dockerfile with instructions.

* Typo.
2020-06-04 20:06:29 -04:00
Daniel Lemire 52f44de257 This introduces a tiny simplification in number parsing. (#910)
* This introduces a tiny simplification in number parsing.

* Removing unnecessary function.

Co-authored-by: Daniel Lemire <lemire@gmai.com>
2020-06-04 17:13:02 -04:00
John Keiser ae6dddfff4 Merge pull request #903 from simdjson/jkeiser/dom-parser-implementation
Move parser state to implementation-specific class
2020-06-04 13:09:57 -07:00
Daniel Lemire 539f555e23 We no longer use make 2020-06-02 16:45:30 -04:00
John Keiser b75fa26dc1 Move containing_scope and ret_address to .cpp 2020-06-01 12:15:55 -07:00
John Keiser 3d22a2d845 One weird trick: set a bogus error value in the parser impl
This makes us faster under both gcc and clang somehow.
2020-06-01 12:15:55 -07:00
John Keiser 1aab4752e2 Store all parser state in the implementation 2020-06-01 12:15:54 -07:00
John Keiser 86f8a4a9d2 Don't set parser.valid or parser.error
This regresses performance and is ONLY here because the next
two commits are here; this lets us see the impact of removing
parser.error separately from the impact of the next commit.
2020-06-01 12:14:09 -07:00
John Keiser db2cb061cb Remove on_error function
Solely here to make the next patch smaller and more isolatable
2020-06-01 12:14:09 -07:00
John Keiser 6a71b24495 Reuse stored buf and len from parser 2020-06-01 12:14:09 -07:00
John Keiser 84712a8bbc Store buf and len in parser implementation 2020-06-01 12:14:09 -07:00
John Keiser b86fb95306 Rename doc_parser -> parser 2020-06-01 12:14:09 -07:00
John Keiser a3a9bde83e Move DOM parsing into concrete interface implementation 2020-06-01 12:14:09 -07:00
Daniel Lemire 2fe2dd170b The "competition tests" are being made portable (#907)
* More portable competition

* This will enable SIMDJSON_COMPETITION everywhere by default.

* Minor fixes
2020-05-31 20:34:06 -04:00
yoannlr f772bf4fbc Port tools to cxxopts (#904)
* Port tools to cxxopts

* Fix minify tool architecture argument

* Fix wrong return code in json2json

* Change return codes

* Better handling of the errors.

* Updating to latest version.

* cxxopts outside of SIMDJSON_COMPETITION

Co-authored-by: Daniel Lemire <lemire@gmail.com>
2020-05-29 15:39:23 -04:00
myd7349 ac0c3093f4 Fix build error on UWP (#896)
For x64-uwp, size_t is 64-bit, DWORD is 32-bit.
When /WX compiler option is specified, error occurs.
2020-05-25 09:49:24 -04:00
Daniel Lemire 12150baa5e Using just ASCII. (#899)
* Using just ASCII.

* Let us prune checkperf.

* Moving the description of lookup2 to the HACKING.md file.
2020-05-21 21:59:06 -04:00
John Keiser 219b02c1e5 Merge pull request #900 from simdjson/jkeiser/delay-start-element
Don't write the start element at all until the end
2020-05-21 14:57:54 -07:00
John Keiser 4551e60f8b Don't write start object/array until the end 2020-05-21 14:28:47 -07:00
John Keiser ea842e78af Merge pull request #895 from simdjson/jkeiser/logger
Add logging to stage 2
2020-05-21 14:11:01 -07:00
John Keiser 5651fbedc4 Add logging to stage 2 2020-05-21 09:47:19 -07:00
John Keiser 2f87dfd4a9 Merge pull request #897 from myd7349/fix-ninja-build
Fix Ninja build
2020-05-21 09:44:39 -07:00
myd7349 332dd76867 Fix Ninja build
When using Ninja as generator, it failed to build:
$ cmake .. -G Ninja
$ ninja
> ninja: error: '/jsonexamples/generated/miss-templates/*.txt', needed by 'jsonexamples/generated/utf-8.json', missing and no known rule to make it
2020-05-21 12:29:39 +08:00
Daniel Lemire d2c9ea8a9a Detect bash instead of relying on MSVC detection. (#894) 2020-05-20 12:13:14 -04:00
Daniel Lemire 40d57da83c fixes issue 891 (#893) 2020-05-20 11:54:53 -04:00
John Keiser 561813eb2a Merge pull request #883 from simdjson/jkeiser/move-include-files
Make include files more fine-grained
2020-05-19 15:48:06 -07:00
John Keiser e6c9dfbd91 Make include files more fine-grained 2020-05-19 14:42:04 -07:00
John Keiser 603b6596af Merge pull request #882 from simdjson/jkeiser/move-cpp-files
Split stage2 into files-per-class
2020-05-19 14:34:01 -07:00
John Keiser 64abc3e86c Include top-level .h files outside #if statements 2020-05-19 13:33:14 -07:00
John Keiser fac42fa3e8 Generate relative filenames properly in amalgamation 2020-05-19 13:32:38 -07:00
John Keiser 7ad4020829 Make main compilation chunks into .cpp files 2020-05-19 13:32:35 -07:00
John Keiser 72ab0d11ff Move stage 1 and 2 files to their own directories 2020-05-19 13:30:34 -07:00
John Keiser 4ea866f050 Move stage2 classes into their own files 2020-05-19 13:30:34 -07:00
John Keiser a476531524 Share ref_address everywhere it's used 2020-05-19 13:30:34 -07:00
John Keiser e7e6ac5bb3 Merge pull request #887 from simdjson/jkeiser/checkperf-less
Don't repeat circleci checkperf tests on drone
2020-05-19 13:21:39 -07:00
Daniel Lemire f346362b00 The jsonstats utility becomes ever more powerful. (#890) 2020-05-19 10:31:27 -04:00
John Keiser d9ba455695 Don't repeat circleci checkperf tests on drone 2020-05-15 04:03:06 -07:00
Daniel Lemire 8927a0561f Obvious fix. (#885) 2020-05-14 20:39:44 -04:00
Daniel Lemire e03c5e9f23 We should guard the include (#881) 2020-05-13 20:02:46 -04:00
Daniel Lemire 1f79200db8 This fixes how we count integers in jsonstats. (#878)
* This fixes how we count integers in jsonstats.
2020-05-13 09:31:32 -04:00
Daniel Lemire c009e4a57d Fuzzing should not require loading lots of complicated dependencies (#879)
* I don't think we need google benchmark as part of the fuzzer

* I don't think we should load the "competition" for fuzzing.
2020-05-13 08:30:09 -04:00
John Keiser c615d52cf4 Merge pull request #876 from simdjson/jkeiser/doc-writing-stage-2
Move tape writes into stage 2 code
2020-05-12 10:05:40 -07:00
John Keiser dbb3316511 Move current_string_buf_loc to stage 2 2020-05-11 06:11:32 -07:00
John Keiser cd6f204c77 Move write_tape() to stage 2 code 2020-05-11 06:09:48 -07:00
John Keiser 269131ed21 Move on_number_* to stage 2 code 2020-05-11 06:04:54 -07:00
John Keiser 65d784e88e Move on_start/end_string to stage 2 code 2020-05-11 05:49:40 -07:00
John Keiser 35afb6cae0 Move on_error, on_success to stage 2 code 2020-05-11 05:46:18 -07:00
John Keiser 27bce09be8 Consolidate start_scope/end_scope 2020-05-11 05:40:02 -07:00
John Keiser 4f25b6ac0c Move on_end_* to stage 2 code 2020-05-11 05:34:49 -07:00
John Keiser 3d5ed1a7e3 Move on_start_* to stage 2 code 2020-05-11 05:30:35 -07:00
John Keiser a03115a4a6 Move end_scope to stage 2 code 2020-05-11 05:24:12 -07:00
John Keiser 7219d28a31 Call end_scope directly from stage 2 code 2020-05-11 05:20:04 -07:00
John Keiser 0875bce68f Don't pass depth to on_end_* 2020-05-11 05:15:39 -07:00
John Keiser 54fe302907 Don't pass depth to end_scope 2020-05-11 05:06:41 -07:00
John Keiser edaa8f811f Move on_start_* depth management to stage 2 code 2020-05-11 05:03:25 -07:00
John Keiser 2c8fd109de Move increment_count to stage 2 2020-05-11 04:58:50 -07:00
John Keiser 07fe7ad1a2 Use the same increment_count() everywhere 2020-05-11 04:48:15 -07:00
John Keiser 16d88cc095 Don't pass depth to increment_count 2020-05-11 04:15:02 -07:00
Daniel Lemire 2a6e6b3dbd Cleaning string_view (#872)
* Cleaning string_view

* Corrected typo

* Alignment.
2020-05-10 16:05:52 -04:00
Daniel Lemire 0c19848230 Fixes issue 871 (#873) 2020-05-10 15:56:49 -04:00
Daniel Lemire 3c3a4db54e Compile under Visual Studio for ARM64 (#861)
* Modifications so that we can compile under Visual Studio for ARM64
* Let us throw appveyor at this beast.
2020-05-06 23:08:10 -04:00
Daniel Lemire 0e6bd2224f Fixes issue 863 (#864)
* Fixes issue 863
2020-05-06 22:38:49 -04:00
John Keiser a64d2f4673 Merge pull request #857 from simdjson/jkeiser/benchfeatures
Make benchfeatures work again
2020-05-05 12:34:49 -07:00
John Keiser 1e8a54af0b Fix benchfeatures.rb on Ruby 1.9 2020-05-05 11:52:07 -07:00
John Keiser aa53d8708e Generate test data when tests are built 2020-05-05 11:29:41 -07:00
John Keiser 8c600ca553 Make benchfeatures work again 2020-05-05 09:39:29 -07:00
John Keiser 25fe6d7dde Merge pull request #859 from simdjson/jkeiser/vsquickstart
Eliminate Intellisense errors and warnings in new VS project
2020-05-05 08:25:13 -07:00
John Keiser afb369950c Disable Intellisense-only warnings in simdjson.h/cpp 2020-05-04 11:47:04 -07:00
John Keiser d7f133c24c Reamalgamate 2020-05-04 11:36:00 -07:00
John Keiser 5312fd30e5 Fix CRT_SECURE warnings in clang 2020-05-04 11:36:00 -07:00
John Keiser 23dd0bdaa1 Remove /nologo MSVC flag 2020-05-04 11:35:57 -07:00
John Keiser 1d06624d38 Unset /D_CRT_SECURE_NO_WARNINGS
- Also localize DISABLE_DEPRECATED_WARNING so that we catch other
  deprecations
2020-05-04 11:35:05 -07:00
Pavel P d40069a018 Disable deprecation warnings for VS builds
fopen/getenv are standard c++ that are not deprecated.
2020-05-04 11:34:00 -07:00
John Keiser 73e27bdd48 Merge pull request #852 from furkanusta/cmake-flags
CMake: Separate public and private compilation flags
2020-05-03 08:55:52 -07:00
Furkan Usta 064eb0b24f CMake: Make simdjson-internal-flags subsume simdjson-flags 2020-05-03 02:48:29 +03:00
Furkan Usta af968c5b44 Merge branch 'master' of github.com:simdjson/simdjson into cmake-flags 2020-05-03 02:12:23 +03:00
John Keiser f93dbe51e2 Merge pull request #855 from simdjson/dlemire/minorreformatwithclangformat
A gift to John.
2020-05-02 13:55:43 -07:00
Daniel Lemire 1c34707925 A gift to John. 2020-05-02 15:01:22 -04:00
John Keiser deaca58504 Merge pull request #851 from furkanusta/cmake-checkperf
Propagate some CMake variables to checkperf
2020-05-02 09:22:48 -07:00
John Keiser 1d519aa9cb Merge pull request #854 from furkanusta/fix808
Add path information back to amalgamate.sh (Fixes #808)
2020-05-02 09:21:53 -07:00
John Keiser 191faeae70 Merge pull request #853 from furkanusta/windows-parsingchecks
Enable numberparsingcheck and stringparsingcheck on MSVC
2020-05-02 09:19:47 -07:00
John Keiser 1153aaf55b Merge pull request #850 from furkanusta/cmake-taketwo
Only install singleheader/simdjson.h as part of the public API
2020-05-02 09:06:06 -07:00
Furkan Usta 292cb5a5af Add path information back to amalgamate.sh (Fixes #808) 2020-05-02 18:00:42 +03:00
Furkan Usta 1e9488d4a6 Remove Microsoft comment regarding dirent in parsingchecks 2020-05-02 16:01:30 +03:00
Furkan Usta ff1d77ead9 Add NOMINMAX to parsingchecks 2020-05-02 15:33:53 +03:00
Furkan Usta 977e1a94b2 Use dirent_portable.h only in MSVC 2020-05-02 15:16:50 +03:00
Furkan Usta 60ee5fc844 Enable numberparsingcheck and stringparsingcheck on MSVC 2020-05-02 15:12:30 +03:00
Furkan Usta 940c8fcb5e Fix: simdjson-private-flags to simdjson-internal-flags 2020-05-02 05:23:53 +03:00
Furkan Usta 71e0148eb4 CMake: Link simdjson-fuzzer to simdjson-source as before
simdjson target adds extra definitions which MSVC doesn't like
2020-05-02 05:21:57 +03:00
Furkan Usta 293c104cc4 CMake: Separate public and private compilation flags
simdjson-internal-flags for macros and warnings
simdjson-flags for pthread, sanitizer, and libcpp
2020-05-02 04:08:47 +03:00
Furkan Usta 5a3035bb72 Propagate some CMake variables to checkperf
Although it passes user-defined options, if the project is build in Debug mode or with Clang (since
CXX defaults to gcc on Linux) results can flactuate
2020-05-02 02:40:13 +03:00
Furkan Usta e04cbd71d0 Only install singleheader/simdjson.h as part of the public API 2020-05-02 01:44:11 +03:00
Daniel Lemire fa4ce6a8bc There is confusion between gigabytes and gigibytes. Let us standardize throughout. (#838)
* There is confusion between gigabytes and gigibytes.

* Trying to be consistent.
2020-05-01 12:16:18 -04:00
Daniel Lemire 9863f62321 Trying to avoid unused warnings in isa detection. (#846) 2020-05-01 11:43:31 -04:00
John Keiser 7cd1f7dbd5 Merge pull request #840 from simdjson/jkeiser/conanimages
Use gcc9 and clang9 where possible
2020-05-01 08:40:57 -07:00
Daniel Lemire 8c45a18524 Hiding cpuid_*_bit as well as related enum. (#843) 2020-04-30 21:08:08 -04:00
Daniel Lemire 8cb383ed45 Update AUTHORS 2020-04-30 19:49:20 -04:00
Daniel Lemire 7d1305b169 Update AUTHORS 2020-04-30 19:49:01 -04:00
Daniel Lemire 24ab1f32e4 adding Furkan Taşkale 2020-04-30 19:48:36 -04:00
Daniel Lemire 073ad0dada This function is unused. (#842) 2020-04-30 19:45:45 -04:00
John Keiser f43b6a0675 Use gcc9 and clang9 where possible 2020-04-30 15:35:38 -07:00
Daniel Lemire fc1ddcd2f8 Faster case-insensitive comparisons. (#837)
* Faster case-insensitive comparisons.
2020-04-30 15:52:28 -04:00
John Keiser e7f774f964 Merge pull request #836 from furkanusta/fix830
Make library consumable after CMake installation (Fixes #830)
2020-04-30 11:34:08 -07:00
John Keiser cb49af1ea5 Merge pull request #835 from simdjson/jkeiser/enable-google-benchmarks
Default SIMDJSON_GOOGLE_BENCHMARKS to ON.
2020-04-30 11:22:38 -07:00
Furkan Usta 73d7d704c1 CMake: Remove export_private_library
Since we are exporting all the targets as part of the main simdjson target we do not need private
exports anymore
2020-04-30 02:06:19 +03:00
John Keiser 8b89232f12 Merge pull request #834 from simdjson/jkeiser/normal-checkperf-windows
Compare against master on Windows
2020-04-29 15:28:06 -07:00
John Keiser c3dec1a5ea Default SIMDJSON_GOOGLE_BENCHMARKS to ON. 2020-04-29 15:21:43 -07:00
Furkan Usta 44b06d70e8 CMake: Link Threads the old-style
If linked against Threads::Threads target while building static libraries, cmake cannot find the
threads library while trying to use the installed target afterwards
2020-04-29 23:47:36 +03:00
Furkan Usta eee07e6cfd Use the same export name for all targets 2020-04-29 23:47:27 +03:00
Daniel Lemire 5051c27c3d Update HACKING.md 2020-04-29 15:57:37 -04:00
John Keiser 76f3506ac5 Compare against master on Windows 2020-04-29 12:55:53 -07:00
Daniel Lemire 5d7a84fad7 Update HACKING.md 2020-04-29 14:05:50 -04:00
Daniel Lemire dec161ed26 Update CONTRIBUTORS 2020-04-29 13:57:07 -04:00
Nong Li 0f9dbf84b7 Fix incorrect check for case insensitive key lookup (#824) 2020-04-29 13:55:28 -04:00
Daniel Lemire f0d5337818 Adding independent benchmarks using Google Benchmark (#826)
* Adding independent benchmarks using Google Benchmark
2020-04-29 13:53:54 -04:00
Daniel Lemire 4cd9de5c37 This will change the default of the parse benchmark so that it work over hot buffers (#827)
* This will change the default of the parse benchmark so that it work over hot buffers
by default, thus omitting memory allocation as part of the benchmark.

* Everyone should be using '-H' from now on.
2020-04-29 13:43:27 -04:00
John Keiser 76b0bfa7f5 Merge pull request #816 from simdjson/jkeiser/gitignore
Remove unneeded .gitignores
2020-04-28 15:19:57 -07:00
John Keiser 32d6b0eed4 Merge pull request #825 from simdjson/jkeiser/documents-sec
Don't include benchmark overhead in documents/s
2020-04-28 15:19:18 -07:00
John Keiser 127d962271 Remove unneeded .gitignores
Now that cmake is the only build system, we don't generate
binaries in the source tree anymore. Amalgamate also doesn't
leave anything around.
2020-04-28 13:21:30 -07:00
John Keiser 92d7af0881 Don't include benchmark overhead in documents/s 2020-04-28 13:15:01 -07:00
Daniel Lemire af12066f77 Update README.md 2020-04-28 11:38:34 -04:00
Daniel Lemire 2a1f8fa8f1 Provides support for clang under Windows. (#817) 2020-04-27 22:09:27 -04:00
Daniel Lemire 04e47bde84 Update basics.md 2020-04-27 16:16:40 -04:00
John Keiser 49da7e74cd usage.md -> basics.md (#823) 2020-04-27 16:03:19 -04:00
John Keiser 6ac47734c0 Only build fuzzers when fuzzing. (#822) 2020-04-27 16:02:19 -04:00
John Keiser 0e6ea76e88 Make checkperf work on Windows (#799)
* Make command line arguments work for Windows

* Run checkperf on Windows
2020-04-27 14:20:05 -04:00
PavelP 0514588175 Improves clang-cl build with Visual Studio (#809) 2020-04-27 08:59:32 -04:00
John Keiser 59d1212039 Merge pull request #803 from simdjson/jkeiser/windows-ci-parallel
Run Windows tests and builds in parallel
2020-04-26 12:07:54 -07:00
John Keiser d61cca6720 Run Windows tests and builds in parallel 2020-04-26 10:12:15 -07:00
John Keiser 8c74e88f16 Merge pull request #740 from pps83/master-amalgamate
Make amalgamated functionally equivalent to src/simdjson.cpp
2020-04-26 08:17:49 -07:00
PavelP 46cf512032 Add cmake /build dir to gitignore (#800)
+ ignore build* top level dirs
2020-04-26 10:11:16 -04:00
Pavel P 24a185d26b Amalgamate src/simdjson.cpp as-is
amalgamation.sh shouldn't change contents of src/simdjson.cpp by forcing dmalloc.h that didn't exist in non-amalgamated version and shouldn't change order of includes by placing simdjson.h at the top

fixes #739
2020-04-26 08:27:19 +06:00
Daniel Lemire b99a7344c9 missing spaces. 2020-04-25 22:26:18 -04:00
Daniel Lemire c6a4fb1e13 Update README.md 2020-04-25 22:21:12 -04:00
Daniel Lemire e2718fe845 Update HACKING.md 2020-04-25 11:30:54 -04:00
Daniel Lemire 76314280cb Update basics.md 2020-04-25 11:24:41 -04:00
Daniel Lemire d6716218bd details. 2020-04-24 20:12:02 -04:00
Daniel Lemire 9371a92122 Update CONTRIBUTING.md 2020-04-24 19:52:16 -04:00
Daniel Lemire e8b030ad17 Fixes issue https://github.com/simdjson/simdjson/issues/774 (#794) 2020-04-24 11:36:00 -04:00
Daniel Lemire e0180b4849 Update issue templates 2020-04-24 09:57:10 -04:00
Daniel Lemire 3901bbb401 Update README.md 2020-04-24 09:33:29 -04:00
Daniel Lemire 76bebfd798 Update issue templates 2020-04-24 09:32:26 -04:00
Daniel Lemire 3013166d8d Update issue templates 2020-04-24 09:26:01 -04:00
Daniel Lemire 8596e702ac Delete custom.md 2020-04-24 09:20:31 -04:00
Daniel Lemire 414bf4a296 Update issue templates 2020-04-24 09:19:37 -04:00
Daniel Lemire 0daa01edef Update issue templates 2020-04-24 09:18:22 -04:00
Daniel Lemire 98abd96075 Update CONTRIBUTING.md 2020-04-24 09:09:39 -04:00
Daniel Lemire 8e3fc826e2 adding doxygen badge 2020-04-24 07:19:16 -04:00
Daniel Lemire c750095241 Trying to improve a bit. (#791)
* Trying to improve a bit.

* Correcting typo
2020-04-23 22:36:08 -04:00
John Keiser 2a0c0c0ad2 Merge pull request #788 from simdjson/jkeiser/remove-makefile
Remove Makefile
2020-04-23 19:33:38 -07:00
John Keiser 92f3bb89c3 Remove Makefile and update CI not to use it 2020-04-23 19:33:20 -07:00
Daniel Lemire ac0e6c5e6e Update basics.md 2020-04-23 22:01:20 -04:00
Daniel Lemire f397b6fedf Another example. (#790)
* Another example.

* Adding a reference to error chaining.
2020-04-23 21:48:41 -04:00
John Keiser 1d069e5077 Split simdjson-flags and cmakecache into include files 2020-04-23 17:06:35 -07:00
John Keiser c5684a6278 Merge pull request #786 from simdjson/jkeiser/sdl-warnings
Enable /sdl warnings on Windows
2020-04-23 17:04:32 -07:00
Daniel Lemire f3ac0be0e6 Merge branch 'master' of github.com:simdjson/simdjson 2020-04-23 18:39:56 -04:00
Daniel Lemire 18c9468af5 Fixed typo 2020-04-23 18:39:32 -04:00
John Keiser 32bc0da362 Regenerate singleheader 2020-04-23 15:37:08 -07:00
Daniel Lemire c9a3800ce7 Let us drop libc++ (#787) 2020-04-23 18:33:38 -04:00
ostri d4239aaa8f default initialisaiton (#779)
* padded_string.* default initialisation
parsedjson_iterator - copy constructor; depth_index not necessary
2020-04-23 18:32:11 -04:00
Daniel Lemire 4f72d5cfac This adds another example (#785) 2020-04-23 18:29:28 -04:00
John Keiser 66acab4130 Enable /sdl warnings on Windows 2020-04-23 15:12:21 -07:00
John Keiser 9e9e3373e0 Merge pull request #784 from simdjson/jkeiser/reamalgamate
Remalgamate when source/header files change
2020-04-23 13:57:53 -07:00
Daniel Lemire 502fee1b45 Fixes the way conditions are checked on variables so it is correct. (#780) 2020-04-23 16:01:40 -04:00
Daniel Lemire 4d0c7d706d Warn 32-bit users about their doom. (#783) 2020-04-23 16:01:19 -04:00
John Keiser 6cd418b60a Automatically re-amalgamate when source/headers change 2020-04-23 12:17:39 -07:00
John Keiser a3b39dfd1a Test against headers amalgamated from current source 2020-04-23 12:17:37 -07:00
Daniel Lemire 74da47e286 Building from the single-header files alone everywhere, including under Visual Studio (#778)
* The idea here is to build from the single-header files alone.

* Testing the headers from the repo.
2020-04-23 15:07:26 -04:00
John Keiser 587ba9bec0 Merge pull request #728 from simdjson/jkeiser/cmake-fuzz-noexceptions
Compile fuzzers without exceptions, run as part of tests
2020-04-23 10:13:33 -07:00
Daniel Lemire 382392e03b This should enable -Weffc++ (#777)
* Enabling -Weffc++
2020-04-23 13:03:04 -04:00
John Keiser 409948a0f9 Update amalgamated headers 2020-04-23 09:19:26 -07:00
Daniel Lemire 34919ca394 Update README.md 2020-04-23 12:04:46 -04:00
Daniel Lemire 0d1c574cb1 A few more changes... (#775)
* More nitpicking.
2020-04-23 11:36:52 -04:00
Daniel Lemire c564815931 Merge branch 'master' of github.com:simdjson/simdjson 2020-04-23 11:30:09 -04:00
Daniel Lemire f6fb667ac1 Being more explicit. 2020-04-23 11:25:20 -04:00
Daniel Lemire 832bbe734d Extra details. 2020-04-23 11:20:12 -04:00
Daniel Lemire 7a2fda891c Merge branch 'master' into jkeiser/cmake-fuzz-noexceptions 2020-04-23 10:29:14 -04:00
Daniel Lemire e50c239a2e Added Matjaž Ostroveršnik. 2020-04-23 10:18:56 -04:00
Daniel Lemire cc7c8d92da We do not use the CC compiler. 2020-04-23 10:14:19 -04:00
ostri 87acab0846 elimination of most of g++ -Weffc++ warnings (#764)
Co-authored-by: Matjaž Ostroveršnik <ostri@localhost.localdomain>
Co-authored-by: Daniel Lemire <lemire@gmail.com>
2020-04-23 10:06:44 -04:00
John Keiser f43459d476 Merge pull request #759 from simdjson/jkeiser/wconversion
Compile with conversion warnings enabled
2020-04-22 20:53:20 -07:00
Daniel Lemire e030f02776 Merge branch 'master' into jkeiser/wconversion 2020-04-22 22:03:34 -04:00
John Keiser 10f2d01e7f Run most build flavors on VS2019 (#761) 2020-04-22 21:59:45 -04:00
Daniel Lemire 80dbf9a32a We should not enable checkperf on anything but Linux. (#762) 2020-04-22 21:54:03 -04:00
Daniel Lemire 185274e70f Let us see if we can test with libc++. (#732)
* Let us see if we can test with libc++.
* Fixed spacing.
2020-04-22 21:24:42 -04:00
Daniel Lemire f0ac55ec0c testing on freebsd (#768)
* Adding cirrus tests
* Adding cirrus badge.
2020-04-22 21:22:09 -04:00
Daniel Lemire 44544635dd More debugging effort. 2020-04-22 17:55:28 -04:00
Daniel Lemire 3c594b1037 Debugging... 2020-04-22 17:30:19 -04:00
Daniel Lemire ea7100e8c4 More tweaking. 2020-04-22 17:22:46 -04:00
John Keiser a198abc485 Use int as index to reduce cast operations
Decreases the number of instructions per block by almost 1
2020-04-22 14:21:33 -07:00
John Keiser d4a37f6ef5 Enable conversion warnings on Linux and Windows 2020-04-22 14:21:30 -07:00
John Keiser a5c9c31231 Merge pull request #755 from simdjson/jkeiser/windows-deprecation-warning
Reenable deprecation warnings on Windows
2020-04-22 14:18:28 -07:00
Daniel Lemire e3ec78a832 Trying again. 2020-04-22 17:18:08 -04:00
John Keiser a116e68a47 Merge pull request #729 from simdjson/jkeiser/cmake-amalgamate
Add amalgamation support to cmake
2020-04-22 14:16:10 -07:00
Daniel Lemire e7084de166 Let us try this way... 2020-04-22 17:14:57 -04:00
Daniel Lemire 398eda6365 Merge branch 'master' of github.com:simdjson/simdjson 2020-04-22 17:06:10 -04:00
Daniel Lemire 349abf5ee6 Hopeful attempt at using cirrus (for FreeBSD) 2020-04-22 17:05:50 -04:00
John Keiser 4ce40b1975 Reenable _CRT_SECURE_NO_WARNINGS 2020-04-22 10:46:59 -07:00
Daniel Lemire 536fe28f8f Being explicit regarding the initialization of two member variables. (#765) 2020-04-22 12:46:55 -04:00
John Keiser 3e9e14f4d6 Reenable deprecation warnings on Windows 2020-04-22 08:53:19 -07:00
John Keiser c8140068ad Merge pull request #760 from simdjson/jkeiser/remove-unneeded-wd-flags
Remove unneeded /WD flags on Windows
2020-04-22 08:21:03 -07:00
John Keiser db314bc381 Make fuzzing work without exceptions 2020-04-21 17:33:47 -07:00
John Keiser 499a26b152 Remove /D_CRT_SECURE_NO_WARNINGS on Windows 2020-04-21 16:56:13 -07:00
John Keiser a9cdb5be50 Remove unneeded /WD flags on Windows 2020-04-21 16:32:34 -07:00
Daniel Lemire 5f04208dbd This removes the problematic use of the intrinsic _addcarry_u64 for Visual Studio (#758)
in the ARM 64-bit kernel. This intrinsic does not appear in the documentation
https://docs.microsoft.com/en-us/cpp/intrinsics/arm64-intrinsics?view=vs-2019
and should probably not be used. Note that we expect the compiler to produce
efficient code out of our implementation.
2020-04-21 17:13:22 -04:00
PavelP ffaa292006 Master vs2019 x86 compile fixes (#743)
* Added bitexact implementations of _BitScanForward64 and _BitScanReverse64 for VS2019 32-bit builds

* Added bitexact implementations of _umul128 for VS2019 x86, arm, arm64 builds

* Implement mul_overflow for VS2019 arm64 builds

 + implement mul_overflow using __umulh (msvc/clang results: https://godbolt.org/z/smRwA7)

* Added Win32 for VS2019 to .appveyor.yml

* Update amalgamated headers (fix x86 builds with VS2019)
2020-04-21 14:42:53 -04:00
John Keiser d3e44b1108 Add amalgamation support to cmake 2020-04-20 19:50:51 -07:00
John Keiser fbf274a42b Merge pull request #727 from simdjson/jkeiser/cmake-checkperf
Add checkperf to cmake
2020-04-20 19:45:45 -07:00
Daniel Lemire d94cd65dfd We used to have a requirements section which went away. I think it is required. (#749) 2020-04-20 19:03:26 -04:00
Daniel Lemire 3c1b403c4e Fixing typo. 2020-04-20 18:19:38 -04:00
John Keiser 75564453b3 Don't checkperf sanitize, don't do sanitize-gcc7 2020-04-20 11:23:19 -07:00
John Keiser 3091e2dc0e Add fallback, westmere and unthreaded checkperf 2020-04-20 11:18:40 -07:00
John Keiser fc50a36cc5 Make checkperf build master with the same options 2020-04-20 11:14:46 -07:00
John Keiser 9bf9fba2ec Add checkperf to cmake 2020-04-20 11:14:46 -07:00
John Keiser 121615da70 Merge pull request #753 from simdjson/jkeiser/fix-cmake-error
Fix cmake error when SIMDJSON_COMPETITION=OFF
2020-04-20 11:11:57 -07:00
John Keiser 53d28a713c Fix cmake error when SIMDJSON_COMPETITION=OFF 2020-04-20 10:49:40 -07:00
John Keiser cf37704193 Merge pull request #737 from simdjson/jkeiser/sanitize-gcc-9
Run sanitize using gcc 9
2020-04-20 10:20:57 -07:00
Daniel Lemire 38289fe381 Tweaking a sentence (#747) 2020-04-20 11:46:02 -04:00
John Keiser f9337a1111 Update amalgamated headers 2020-04-19 11:38:02 -07:00
John Keiser 6d059b479f Add sanitize-gcc9 test 2020-04-19 10:55:50 -07:00
John Keiser b6e23b2d3e Compile and run tests in parallel (-j) 2020-04-19 10:55:23 -07:00
John Keiser e5e6a46c37 Consolidate multi-implementation tests
Uses SIMDJSON_FORCE_IMPLEMENTATION to switch the implementation at test
time.
2020-04-19 09:59:49 -07:00
John Keiser 22b9a53bef Add SIMDJSON_FORCE_IMPLEMENTATION 2020-04-18 18:21:56 -07:00
John Keiser 3be81e3206 Merge pull request #720 from simdjson/jkeiser/prune-circle-tests
Run fewer redundant steps and configs in CircleCI
2020-04-17 13:02:54 -07:00
John Keiser ff09b6c824 Run fewer redundant steps and configs in CI 2020-04-17 12:23:05 -07:00
John Keiser a8e892ba90 Merge pull request #718 from simdjson/jkeiser/cmake-werror
Treat warnings as errors
2020-04-16 17:48:34 -07:00
John Keiser 289cc3e7a0 Treat warnings as errors during compilation 2020-04-15 19:59:38 -07:00
John Keiser 7480b87e07 Merge pull request #693 from simdjson/jkeiser/cmake-quickstartcpp
Add C++11 tests to cmake
2020-04-15 19:53:14 -07:00
Daniel Lemire befa6423be This massively improves the performance of tight loops relying on a type() call. (#721)
* This massively improves the performance of tight loops relying on a type() call.

* Adding a few more benchmarks
2020-04-15 20:45:40 -04:00
John Keiser fd418f568c Fix c++11 warnings on clang
- namespace x::y is C++17
- static_assert requires message in C++11
2020-04-15 17:27:48 -07:00
John Keiser 09cf18a646 Add C++11 tests to cmake
- Add simdjson-flags target so callers don't have flags forced on them
2020-04-15 17:26:25 -07:00
Daniel Lemire 326c175dcb Massive performance boost for get<double>. (#719)
* Massive performance boost for get<double>.
2020-04-15 20:09:45 -04:00
Daniel Lemire 6d7c77ddc1 Let us try to check with the exceptions disabled. (#707)
* Tweaking code so that we can run all tests with exceptions off.
* Removing SIMDJSON_DISABLE_EXCEPTIONS
2020-04-15 16:45:36 -04:00
Daniel Lemire efd706528b Minor tweaks to the CMake. 2020-04-15 10:19:05 -04:00
Daniel Lemire b523c43927 Can we provide a size() function to arrays and objects? (eager approach) [TO BE MERGED] (#690)
* This is an implementation of "size()" for arrays and objects.
* Adding benchmark
* Adding a size() remark in the documentation.
* Extending size() to result types.
2020-04-15 10:15:48 -04:00
Paul Dreik 75545ff70d ref qualify parser methods to avoid use of dangling objects (#703)
To avoid using data belonging to a temporary, the parse functions are ref qualified to get a compile error if used on an rvalue. See https://github.com/simdjson/simdjson/issues/696

Compilation tests are also added, to make sure bad usage fails to compile.

Reviewed by jkeiser.
2020-04-15 09:57:52 +02:00
Daniel Lemire 3c6ef83046 Trying to correct the documentation so that it actually describes how the code behaves. (Attempt two) (#712)
* Trying to correct the documentation so that it actually describes how the code behaves.

* tweaking the wording.

* Improving.

* Removing confusing sentence.

* Fixing formatting.

* Now with working example, tested.

* Added a smaller piece of code
2020-04-14 22:31:21 -04:00
John Keiser b9ac0a79f1 Merge pull request #715 from simdjson/jkeiser/thorough-type-tests
Test more variants of cast, get, etc.
2020-04-14 16:08:36 -07:00
Daniel Lemire 8539896f3d It is inconvenient to be unable to print a padded_string. (#713)
* It is inconvenient to be unable to print a padded_string.

* Allows us to print the padded_string even when it is embedded in result object when exceptions are enabled.
2020-04-14 19:07:32 -04:00
John Keiser a3b508ceff Test get<>(), exception vs. no exception, explicit vs. implicit cast 2020-04-14 13:18:42 -07:00
Daniel Lemire 334a486737 Tweaking the doxygen. (#700)
* Tweaking the doxygen.

* Fixing typo.
2020-04-14 11:31:46 -04:00
Daniel Lemire d7370cc916 Let us document the relationship between a parser instance and the parsed document. (#699) 2020-04-14 08:30:06 -04:00
Paul Dreik 92c34f7f38 do not use deprecated apis in the fuzzers (#705)
* move from deprecated interface in fuzz dump raw tape

* update fuzz_dump to the non deprecated replacement

* replace use of deprecated api

* hopefully fix windows build
2020-04-14 07:45:30 +02:00
Paul Dreik 93328c8d6d improve the fuzzer documentation, refresh links (#697) 2020-04-12 17:49:40 -04:00
Paul Dreik 5710ec13d4 switch to clang 9 in the github action (#695)
The upstream convenience script from llvm does not support installing clang 8 anymore.
2020-04-12 20:02:45 +02:00
Paul Dreik fa637fcecb Enable the minifier fuzzer (fixes #530) (#694)
This enables the minify fuzzer, which has been disabled because it did not pass the oss-fuzz instrumentation test. Now it does, after changes in simdjson (https://github.com/lemire/simdjson/issues/186).

 * get minify running (api change)
 * disable benchmarks when compiling fuzzers
 * catch exceptions from the minify fuzzer
 * enable repeated corpus creation without recursive inclusion of zip
 * remove leftover comment
2020-04-12 18:47:24 +02:00
Daniel Lemire 4af7d6f108 Disabling threads on apple's hardware when optimizer is turned off (#692)
* Disabling threads on apple's hardware.

* Turns out that you can have your bread, your butter and you cake too!
2020-04-10 18:41:05 -04:00
John Keiser 0fd159dadb Merge pull request #689 from simdjson/jkeiser/cmake-test
Add most CI tests to cmake
2020-04-09 16:12:32 -07:00
John Keiser 1ff22c78b3 Add quickstart to cmake 2020-04-09 14:56:54 -07:00
John Keiser ceb1def55c Add quicktests, slowtests to cmake
- Also add testjson2json.sh
- Move test scripts to tests directory to consolidate concerns
2020-04-09 14:21:45 -07:00
John Keiser 893a1d8306 Merge pull request #685 from simdjson/jkeiser/cmake-competition
Add parsing competitions to cmake
2020-04-09 11:25:12 -07:00
John Keiser 3c91690e55 Don't run parsing competitions on Windows
(They currently use linux-specific stuff.)
2020-04-09 08:52:29 -07:00
John Keiser 6835dd73bc Only apply compile flags to simdjson 2020-04-09 08:52:29 -07:00
John Keiser 7317fe1440 Don't reinitialize submodules
Add ability to turn competitive benchmarks off (no need for submodules)
2020-04-09 08:52:29 -07:00
John Keiser 7b58fea911 Add benchmark competitions to cmake 2020-04-09 08:52:29 -07:00
John Keiser c1ff74c9a6 Add issue150 test 2020-04-09 08:52:29 -07:00
John Keiser 6dabfa176a Add competition libraries 2020-04-09 08:52:29 -07:00
John Keiser 0714f5fc67 Create dependencies/CMakeLists.txt 2020-04-09 08:52:29 -07:00
John Keiser 3b1b1bfd48 Merge pull request #684 from simdjson/jkeiser/cmake
Simplify cmake, add more of our tests into it
2020-04-08 16:02:47 -07:00
John Keiser 218c867f46 Disable failing VS2017 tests in cmake 2020-04-08 14:58:28 -07:00
Daniel Lemire 2bc12f9730 Removing useless line. 2020-04-08 17:55:25 -04:00
Daniel Lemire 5e564a8e0c Improving the doxygen. (#687) 2020-04-08 17:53:04 -04:00
John Keiser beaa6a9a7a Create simdjson-windows-headers interface library 2020-04-08 14:52:56 -07:00
John Keiser a9c8224f40 Add numberparsingcheck and stringparsingcheck tests 2020-04-08 14:52:56 -07:00
John Keiser 3dcc188d93 Add more tests to cmake 2020-04-08 14:52:56 -07:00
John Keiser 10b7556a37 Specify cmake tests, benchmarks and tools idiomatically 2020-04-08 14:52:56 -07:00
John Keiser 54b7291c34 Reference simdjson by name, don't specify include files individually 2020-04-08 14:52:55 -07:00
John Keiser 1e30b6e334 Compile under C++ 11 2020-04-08 14:00:13 -07:00
John Keiser 406240bae3 Support C++ 14 2020-04-08 14:00:13 -07:00
Daniel Lemire 74d9b41b7d Minor fixes to our documentation regarding thread safety. (#683)
* Minor fixes to our documentation regarding thread safety.

* A bit more pessimistic.
2020-04-08 16:41:08 -04:00
John Keiser ff0b0c54b7 Merge pull request #682 from simdjson/jkeiser/simplify-cars
Simplify cars example
2020-04-08 10:24:01 -07:00
John Keiser 6eec2d6b4f Simplify cars example 2020-04-05 09:15:20 -07:00
Daniel Lemire 5731c5437a Sanity test. (#675) 2020-04-04 16:39:37 -04:00
Daniel Lemire 04f14ec026 This adds a test for std::ignore (#674) 2020-04-04 11:53:03 -04:00
Dirk Eddelbuettel 12ed6336b1 remove three trailing semicolons that -pedantic dislikes (#673) 2020-04-02 21:06:25 -04:00
Daniel Lemire 3cb79e6977 Trying again. (#671) 2020-04-02 19:24:43 -04:00
John Keiser c5e21a2469 Merge pull request #669 from simdjson/jkeiser/type-switch
Add element.type() for type switching
2020-04-02 15:01:51 -07:00
John Keiser 13aee51011 Add element.type() for type switching 2020-04-02 14:07:19 -07:00
Daniel Lemire 53fca1b5e6 This is a first attempt at fixing issue 660. (#668)
* This is a first attempt at fixing issue 660. The hard part is not the fix by itself, the hard part is to make sure we never get caught with our pants down like that again.

I expect the CI tests will fail. Further commits will solve the issues.

* Setting the rpath properly.

* For the sanitize tests, we want verify the installation.
2020-04-02 15:18:58 -04:00
Daniel Lemire 7dad9fca0f In the future, we will bump the so version with even minor releases. (#664) 2020-04-01 16:08:28 -04:00
John Keiser b249d7c76c Merge pull request #666 from Mengesh/patch-1
Update basics.md
2020-04-01 10:54:01 -07:00
Marko Radišić 4060f64232 Update basics.md
Fix links to singleheader .h and .cpp
2020-04-01 17:13:53 +02:00
M. Zhou 5b2f7d3374 CMake: Bump SOVERSION to "1" due to the breaking changes in API/ABI. (fixes #661) (#662) 2020-04-01 09:53:45 -04:00
604 changed files with 47898 additions and 24928 deletions
+38 -21
View File
@@ -1,29 +1,46 @@
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: 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
+195 -178
View File
@@ -2,215 +2,232 @@ version: 2.1
# Reusable image / compiler definitions
executors:
gcc7:
docker:
- image: gcc:7
environment:
CXX: g++
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
cmake_installed_test_cxx20: # assuming that it was installed, this tries to build using C++20
steps:
- 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++20 -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
executor: gcc7
environment: { CMAKE_TEST_FLAGS: -DSIMDJSON_ENABLE_THREADS=OFF }
# static
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, cmake_installed_test_cxx20 ]
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, cmake_installed_test_cxx20 ]
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, cmake_installed_test_cxx20 ]
# 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, cmake_installed_test_cxx20 ]
# 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 ]
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 tested on GitHub actions
- 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
# testing "just the library"
- justlib-gcc10
# TODO add windows: https://circleci.com/docs/2.0/configuration-reference/#windows
+21
View File
@@ -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 -DSIMDJSON_BASH=OFF -DSIMDJSON_GIT=OFF ..
- make
test_script:
- cd build
- ctest --output-on-failure -E checkperf
+1 -1
View File
@@ -1,7 +1,7 @@
*
!.git
!Makefile
!amalgamation.sh
!amalgamate.sh
!benchmark
!dependencies
!include
+343 -508
View File
@@ -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
+9 -9
View File
@@ -80,15 +80,15 @@
.gitignore export-ignore
# Sources
*.c text diff=c
*.cc text diff=cpp
*.cxx text diff=cpp
*.cpp text diff=cpp
*.c++ text diff=cpp
*.hpp text diff=cpp
*.h text diff=c
*.h++ text diff=cpp
*.hh text diff=cpp
*.c text eol=lf diff=c
*.cc text eol=lf diff=cpp
*.cxx text eol=lf diff=cpp
*.cpp text eol=lf diff=cpp
*.c++ text eol=lf diff=cpp
*.hpp text eol=lf diff=cpp
*.h text eol=lf diff=c
*.h++ text eol=lf diff=cpp
*.hh text eol=lf diff=cpp
# Compiled Object files
*.slo binary
+40
View File
@@ -0,0 +1,40 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug (unverified)
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.
Note that a compiler warning is not a bug.
**To Reproduce**
Steps to reproduce the behaviour: provide a code sample if possible.
If we cannot reproduce the issue, then we cannot address it.
Note that a stack trace from your own program is not enough.
**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]
We support up-to-date 64-bit ARM and x64 FreeBSD, macOS, Windows and Linux systems. Please ensure that your configuration is supported before labelling the issue as a bug. In particular, we do not support legacy 32-bit systems.
**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
+36
View File
@@ -0,0 +1,36 @@
---
name: Feature request
about: Suggest an idea for this project
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 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
+6 -6
View File
@@ -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
+53
View File
@@ -0,0 +1,53 @@
name: MinGW32-CI
on: [push, pull_request]
# 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 parse_many_test jsoncheck basictests numberparsingcheck stringparsingcheck errortests integer_tests pointercheck --verbose
ctest -R "(parse_many_test|jsoncheck|basictests|stringparsingcheck|numberparsingcheck|errortests|integer_tests|pointercheck)" --output-on-failure
+59
View File
@@ -0,0 +1,59 @@
name: MinGW64-CI
on: [push, pull_request]
# 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 parse_many_test jsoncheck basictests numberparsingcheck stringparsingcheck errortests integer_tests pointercheck --verbose
ctest -R "(parse_many_test|jsoncheck|basictests|stringparsingcheck|numberparsingcheck|errortests|integer_tests|pointercheck)" --output-on-failure
cd ..
mkdir build64debug
cd build64debug
cmake -DCMAKE_BUILD_TYPE=Debug -DSIMDJSON_BUILD_STATIC=ON -DSIMDJSON_COMPETITION=OFF -DSIMDJSON_GOOGLE_BENCHMARKS=OFF -DSIMDJSON_ENABLE_THREADS=OFF ..
cmake --build . --target parse_many_test jsoncheck basictests numberparsingcheck stringparsingcheck errortests integer_tests pointercheck --verbose
ctest -R "(parse_many_test|jsoncheck|basictests|stringparsingcheck|numberparsingcheck|errortests|integer_tests|pointercheck)" --output-on-failure
+44
View File
@@ -0,0 +1,44 @@
name: MSYS2-CI
on: [push, pull_request]
jobs:
windows-mingw:
name: ${{ matrix.msystem }}
runs-on: windows-latest
defaults:
run:
shell: msys2 {0}
strategy:
fail-fast: false
matrix:
include:
- msystem: "MINGW64"
install: mingw-w64-x86_64-cmake mingw-w64-x86_64-ninja mingw-w64-x86_64-gcc
type: Release
- msystem: "MINGW32"
install: mingw-w64-i686-cmake mingw-w64-i686-ninja mingw-w64-i686-gcc
type: Release
- msystem: "MINGW64"
install: mingw-w64-x86_64-cmake mingw-w64-x86_64-ninja mingw-w64-x86_64-gcc
type: Debug
- msystem: "MINGW32"
install: mingw-w64-i686-cmake mingw-w64-i686-ninja mingw-w64-i686-gcc
type: Debug
env:
CMAKE_GENERATOR: Ninja
steps:
- uses: actions/checkout@v2
- uses: msys2/setup-msys2@v2
with:
update: true
msystem: ${{ matrix.msystem }}
install: ${{ matrix.install }}
- name: Build and Test
run: |
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=${{ matrix.type }} -DSIMDJSON_BUILD_STATIC=ON -DSIMDJSON_DO_NOT_USE_THREADS_NO_MATTER_WHAT=ON ..
cmake --build . --verbose
ctest -j4 --output-on-failure -E checkperf
+22
View File
@@ -0,0 +1,22 @@
name: Ubuntu 18.04 CI (GCC 7)
on: [push, pull_request]
jobs:
ubuntu-build:
runs-on: ubuntu-18.04
steps:
- uses: actions/checkout@v2
- name: Setup cmake
uses: jwlawson/actions-setup-cmake@v1.0
with:
cmake-version: '3.9.x'
- name: Use cmake
run: |
mkdir build &&
cd build &&
cmake -DSIMDJSON_GOOGLE_BENCHMARKS=ON -DSIMDJSON_BUILD_STATIC=ON -DCMAKE_INSTALL_PREFIX:PATH=destination .. &&
cmake --build . &&
ctest -j --output-on-failure &&
make install &&
echo -e '#include <simdjson.h>\nint main(int argc,char**argv) {simdjson::dom::parser parser;simdjson::dom::element tweets = parser.load(argv[1]); }' > tmp.cpp && c++ -Idestination/include -Ldestination/lib -std=c++17 -Wl,-rpath,destination/lib -o linkandrun tmp.cpp -lsimdjson && ./linkandrun jsonexamples/twitter.json
+22
View File
@@ -0,0 +1,22 @@
name: Ubuntu 20.04 CI (GCC 9)
on: [push, pull_request]
jobs:
ubuntu-build:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- name: Setup cmake
uses: jwlawson/actions-setup-cmake@v1.0
with:
cmake-version: '3.9.x'
- name: Use cmake
run: |
mkdir build &&
cd build &&
cmake -DSIMDJSON_GOOGLE_BENCHMARKS=ON -DSIMDJSON_BUILD_STATIC=ON -DCMAKE_INSTALL_PREFIX:PATH=destination .. &&
cmake --build . &&
ctest -j --output-on-failure &&
make install &&
echo -e '#include <simdjson.h>\nint main(int argc,char**argv) {simdjson::dom::parser parser;simdjson::dom::element tweets = parser.load(argv[1]); }' > tmp.cpp && c++ -Idestination/include -Ldestination/lib -std=c++17 -Wl,-rpath,destination/lib -o linkandrun tmp.cpp -lsimdjson && ./linkandrun jsonexamples/twitter.json
+26
View File
@@ -0,0 +1,26 @@
name: VS16-CI
on: [push, pull_request]
jobs:
ci:
name: windows-vs16
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: 'Run CMake with VS16'
uses: lukka/run-cmake@v2
with:
cmakeListsOrSettingsJson: CMakeListsTxtAdvanced
cmakeListsTxtPath: '${{ github.workspace }}/CMakeLists.txt'
buildDirectory: "${{ github.workspace }}/../../_temp/windows"
cmakeBuildType: Release
buildWithCMake: true
cmakeGenerator: VS16Win64
cmakeAppendedArgs: -DSIMDJSON_COMPETITION=OFF
buildWithCMakeArgs: --config Release
- name: 'Run CTest'
run: ctest -C Release -E checkperf --output-on-failure
working-directory: "${{ github.workspace }}/../../_temp/windows"
+25
View File
@@ -0,0 +1,25 @@
name: VS16-CLANG-CI
on: [push, pull_request]
jobs:
ci:
name: windows-vs16
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: 'Run CMake with VS16'
uses: lukka/run-cmake@v2
with:
cmakeListsOrSettingsJson: CMakeListsTxtAdvanced
cmakeListsTxtPath: '${{ github.workspace }}/CMakeLists.txt'
buildDirectory: "${{ github.workspace }}/../../_temp/windows"
cmakeBuildType: Release
buildWithCMake: true
cmakeGenerator: VS16Win64
cmakeAppendedArgs: -T ClangCL -DSIMDJSON_COMPETITION=OFF -DSIMDJSON_BUILD_STATIC=ON
buildWithCMakeArgs: --config Release
- name: 'Run CTest'
run: ctest -C Release -E checkperf --output-on-failure
working-directory: "${{ github.workspace }}/../../_temp/windows"
+26
View File
@@ -0,0 +1,26 @@
name: VS16-Ninja-CI
on: [push, pull_request]
jobs:
ci:
name: windows-vs16
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
- name: 'Run CMake with VS16'
uses: lukka/run-cmake@v2
with:
cmakeListsOrSettingsJson: CMakeListsTxtAdvanced
cmakeListsTxtPath: '${{ github.workspace }}/CMakeLists.txt'
buildDirectory: "${{ github.workspace }}/../../_temp/windows"
cmakeBuildType: Release
buildWithCMake: true
cmakeGenerator: VS16Win64
cmakeAppendedArgs: -G Ninja -DSIMDJSON_COMPETITION=OFF -DSIMDJSON_BUILD_STATIC=ON
buildWithCMakeArgs: --config Release
- name: 'Run CTest'
run: ctest -C Release -E checkperf --output-on-failure
working-directory: "${{ github.workspace }}/../../_temp/windows"
+11 -102
View File
@@ -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
+3
View File
@@ -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
+2 -1
View File
@@ -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
+60 -67
View File
@@ -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_MINOR 5)
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(SIMDJSON_SEMANTIC_VERSION "0.5.0" CACHE STRING "simdjson semantic version")
set(SIMDJSON_LIB_VERSION "3.0.0" CACHE STRING "simdjson library version")
set(SIMDJSON_LIB_SOVERSION "3" 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 jsonchecker-minefield-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)
+46 -3
View File
@@ -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,20 @@ 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.
- All C macros introduced in public headers need to be prefixed with either `SIMDJSON_` or `simdjson_`.
Tools, tests and benchmarks are not held to these same strict rules.
General Guidelines
----------
Contributors are encouraged to :
@@ -43,11 +56,41 @@ 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.
Style
-----
Our formatting style is inspired by the LLVM style.
The simdjson library is written using the snake case: when a variable or a function is a phrase, each space is replaced by an underscore character, and the first letter of each word written in lowercase. Compile-time constants are written entirely in uppercase with the same underscore convention.
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
-----------------------
+4
View File
@@ -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
View File
@@ -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 . "]
+4 -4
View File
@@ -38,7 +38,7 @@ PROJECT_NAME = simdjson
# could be handy for archiving the generated documentation or if some version
# control system is used.
PROJECT_NUMBER =
PROJECT_NUMBER = "0.5.0"
# 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
+169 -278
View File
@@ -1,33 +1,63 @@
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.
Here is wisdom about how to build, test and run simdjson from within the repository. This is mostly useful for people who plan to contribute simdjson, or maybe study the design.
If you plan to contribute to simdjson, please read our [CONTRIBUTING](https://github.com/simdjson/simdjson/blob/master/CONTRIBUTING.md) guide.
Design notes
------------------------------
The parser works in two stages:
- Stage 1. (Find marks) Identifies quickly structure elements, strings, and so forth. We validate UTF-8 encoding at that stage.
- Stage 2. (Structure building) Involves constructing a "tree" of sort (materialized as a tape) to navigate through the data. Strings and numbers are parsed at this stage.
The role of stage 1 is to identify pseudo-structural characters as quickly as possible. A character is pseudo-structural if and only if:
1. Not enclosed in quotes, AND
2. Is a non-whitespace character, AND
3. Its preceding character is either:
(a) a structural character, OR
(b) whitespace OR
(c) the final quote in a string.
This helps as we redefine some new characters as pseudo-structural such as the characters 1, G, n in the following:
> { "foo" : 1.5, "bar" : 1.5 GEOFF_IS_A_DUMMY bla bla , "baz", null }
Stage 1 also does unicode validation.
Stage 2 handles all of the rest: number parsings, recognizing atoms like true, false, null, and so forth.
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
* simdjson.h: A "main include" that includes files from include/simdjson/. This is equivalent to
the distributed simdjson.h.
* simdjson/*.h: Declarations for public simdjson classes and functions.
* simdjson/inline/*.h: Definitions for public simdjson classes and functions.
* simdjson/*-inl.h: Definitions for public simdjson classes and functions.
* **src:** The source files for non-inlined functionality (e.g. the architecture-specific parser
implementations).
* simdjson.cpp: A "master source" that includes all implementation files from src/. This is
* simdjson.cpp: A "main 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,91 +65,143 @@ 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.
* **.github/workflows:** Definitions for GitHub Actions (CI).
* **singleheader:** Contains generated `simdjson.h` and `simdjson.cpp` that we release. The files `singleheader/simdjson.h` and `singleheader/simdjson.cpp` should never be edited by hand.
* **singleheader/amalgamate.sh:** Generates `singleheader/simdjson.h` and `singleheader/simdjson.cpp` for release (bash script).
* **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.
* **pass*.json:** Files that should pass validation.
* **fail*.json:** Files that should fail validation.
* **jsonchecker/minefield/y_*.json:** Files that should pass validation.
* **jsonchecker/minefield/n_*.json:** Files that should fail validation.
* **jsonexamples:** A wide spread of useful, real-world JSON files with different characteristics
and sizes.
* **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
* **tools:** Source for executables that can be distributed with simdjson. Some examples:
* `json2json mydoc.json` parses the document, constructs a model and then dumps back the result to standard output.
* `json2json -d mydoc.json` parses the document, constructs a model and then dumps model (as a tape) to standard output. The tape format is described in the accompanying file `tape.md`.
* `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.
> **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
multiple files under include/ and src/. The files include/simdjson.h and src/simdjson.cpp are the "spine" for
these, and you can include them as if they were the corresponding singleheader/ files.
Regenerating Single Headers From Master
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-Header Files
---------------------------------------
simdjson.h and simdjson.cpp are not always up to date in master. To ensure you have the latest copy,
you can regenerate them by running this at the top level:
The simdjson.h and simdjson.cpp files in the singleheader directory are not always up-to-date with the rest of the code; they are only ever
systematically regenerated on releases. To ensure you have the latest code, 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
You need to have a working bash on your system.
The amalgamator script is `amalgamate.sh` 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 +209,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 +221,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,213 +233,50 @@ mkdir build
cd build
export CXX=g++-8 CC=gcc-8
cmake ..
make
make test
cmake --build .
ctest
```
### Usage (CMake on 64-bit Windows using Visual Studio)
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$"`.
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).
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 2019)
We assume you have a common 64-bit Windows PC with at least Visual Studio 2019.
- 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 ..` in the shell while in the `build` repository.
- 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`.
### 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.
Though having Visual Studio installed is necessary, one can build simdjson using only cmake commands:
On 64-bit Linux and macOS:
```
$ ./vcpkg install simdjson
```
will build and install `simdjson` as a static library.
On Windows (64-bit):
```
.\vcpkg.exe install simdjson:x64-windows
```
will build and install `simdjson` as a shared library.
```
.\vcpkg.exe install simdjson:x64-windows-static
```
will build and install `simdjson` as a static library.
These commands will also print out instructions on how to use the library from MSBuild or CMake-based projects.
If you find the version of `simdjson` shipped with `vcpkg` is out-of-date, feel free to report it to
`vcpkg` community either by submitting an issue or by creating a PR.
### Usage (Docker)
One can run tests and benchmarks using docker. It especially makes sense under Linux. Privileged
access may be needed to get performance counters.
```
git clone https://github.com/simdjson/simdjson.git
cd simdjson
docker build -t simdjson .
docker run --privileged -t simdjson
```
## Architecture and Design Notes
### Requirements
- 64-bit platforms like Linux or macOS, as well as Windows through Visual Studio 2017 or later.
- Any 64-bit processor:
- AVX2 (i.e., Intel processors starting with the Haswell microarchitecture released 2013 and AMD
processors starting with the Zen microarchitecture released 2017),
- SSE 4.2 and CLMUL (i.e., Intel processors going back to Westmere released in 2010 or AMD
processors starting with the Jaguar used in the PS4 and XBox One),
- 64-bit ARM processor (ARMv8-A NEON): this covers a wide range of mobile processors, including
all Apple processors currently available for sale, going as far back as the iPhone 5s (2013).
- Any 64-bit processor (simdjson has a fallback generic 64-bit implementation that is still super
fast).
- A recent C++ compiler (e.g., GNU GCC or LLVM CLANG or Visual Studio 2017), we assume C++17. GNU
GCC 7 or better or LLVM's clang 6 or better.
- Some benchmark scripts assume bash and other common utilities, but they are optional.
### Scope
We provide a fast parser, that fully validates an input according to various specifications.
The parser builds a useful immutable (read-only) DOM (document-object model) which can be later accessed.
To simplify the engineering, we make some assumptions.
- We support UTF-8 (and thus ASCII), nothing else (no Latin, no UTF-16). We do not believe this is a
genuine limitation, because we do not think there is any serious application that needs to process
JSON data without an ASCII or UTF-8 encoding. If the UTF-8 contains a leading BOM, it should be
omitted: the user is responsible for detecting and skipping the BOM; UTF-8 BOMs are discouraged.
- All strings in the JSON document may have up to 4294967295 bytes in UTF-8 (4GB). To enforce this
constraint, we refuse to parse a document that contains more than 4294967295 bytes (4GB). This
should accommodate most JSON documents.
- As allowed by the specification, we allow repeated keys within an object (other parsers like
sajson do the same).
- [The simdjson library is fast for JSON documents spanning a few bytes up to many megabytes](https://github.com/lemire/simdjson/issues/312).
_We do not aim to provide a general-purpose JSON library._ A library like RapidJSON offers much more
than just parsing, it helps you generate JSON and offers various other convenient functions. We
merely parse the document. This may change in the future.
### Features
- The input string is unmodified. (Parsers like sajson and RapidJSON use the input string as a buffer.)
- We parse integers and floating-point numbers as separate types which allows us to support large signed 64-bit integers in [-9223372036854775808,9223372036854775808), like a Java `long` or a C/C++ `long long` and large unsigned integers up to the value 18446744073709551615. Among the parsers that differentiate between integers and floating-point numbers, not all support 64-bit integers. (For example, sajson rejects JSON files with integers larger than or equal to 2147483648. RapidJSON will parse a file containing an overly long integer like 18446744073709551616 as a floating-point number.) When we cannot represent exactly an integer as a signed or unsigned 64-bit value, we reject the JSON document.
- We support the full range of 64-bit floating-point numbers (binary64). The values range from ` std::numeric_limits<double>::lowest()` to `std::numeric_limits<double>::max()`, so from -1.7976e308 all the way to 1.7975e308. Extreme values (less or equal to -1e308, greater or equal to 1e308) are rejected: we refuse to parse the input document.
- We test for accurate float parsing with a perfect accuracy (ULP 0). Many parsers offer only approximate floating parsing. For example, RapidJSON also offers the option of accurate float parsing (`kParseFullPrecisionFlag`) but it comes at a significant performance penalty compared to the default settings. By default, RapidJSON tolerates an error of 3 ULP.
- We do full UTF-8 validation as part of the parsing. (Parsers like fastjson, gason and dropbox json11 do not do UTF-8 validation. The sajson parser does incomplete UTF-8 validation, accepting code point
sequences like 0xb1 0x87.)
- We fully validate the numbers. (Parsers like gason and ultranjson will accept `[0e+]` as valid JSON.)
- We validate string content for unescaped characters. (Parsers like fastjson and ultrajson accept unescaped line breaks and tabs in strings.)
- We fully validate the white-space characters outside of the strings. Parsers like RapidJSON will accept JSON documents with null characters outside of strings.
### Architecture
The parser works in two stages:
- Stage 1. (Find marks) Identifies quickly structure elements, strings, and so forth. We validate UTF-8 encoding at that stage.
- Stage 2. (Structure building) Involves constructing a "tree" of sort (materialized as a tape) to navigate through the data. Strings and numbers are parsed at this stage.
### Remarks on JSON parsing
- The JSON spec defines what a JSON parser is:
> A JSON parser transforms a JSON text into another representation. A JSON parser MUST accept all texts that conform to the JSON grammar. A JSON parser MAY accept non-JSON forms or extensions. An implementation may set limits on the size of texts that it accepts. An implementation may set limits on the maximum depth of nesting. An implementation may set limits on the range and precision of numbers. An implementation may set limits on the length and character contents of strings.
* JSON is not JavaScript:
> All JSON is Javascript but NOT all Javascript is JSON. So {property:1} is invalid because property does not have double quotes around it. {'property':1} is also invalid, because it's single quoted while the only thing that can placate the JSON specification is double quoting. JSON is even fussy enough that {"property":.1} is invalid too, because you should have of course written {"property":0.1}. Also, don't even think about having comments or semicolons, you guessed it: they're invalid. (credit:https://github.com/elzr/vim-json)
* The structural characters are:
begin-array = [ left square bracket
begin-object = { left curly bracket
end-array = ] right square bracket
end-object = } right curly bracket
name-separator = : colon
value-separator = , comma
### Pseudo-structural elements
A character is pseudo-structural if and only if:
1. Not enclosed in quotes, AND
2. Is a non-whitespace character, AND
3. Its preceding character is either:
(a) a structural character, OR
(b) whitespace.
This helps as we redefine some new characters as pseudo-structural such as the characters 1, G, n in the following:
> { "foo" : 1.5, "bar" : 1.5 GEOFF_IS_A_DUMMY bla bla , "baz", null }
## About the Project
### Bindings and Ports of simdjson
We distinguish between "bindings" (which just wrap the C++ code) and a port to another programming language (which reimplements everything).
- `mkdir build`
- `cd build`
- `cmake ..`
- `cmake --build . -config Release`
- [ZippyJSON](https://github.com/michaeleisel/zippyjson): Swift bindings for the simdjson project.
- [pysimdjson](https://github.com/TkTech/pysimdjson): Python bindings for the simdjson project.
- [simdjson-rs](https://github.com/Licenser/simdjson-rs): Rust port.
- [simdjson-rust](https://github.com/SunDoge/simdjson-rust): Rust wrapper (bindings).
- [SimdJsonSharp](https://github.com/EgorBo/SimdJsonSharp): C# version for .NET Core (bindings and full port).
- [simdjson_nodejs](https://github.com/luizperes/simdjson_nodejs): Node.js bindings for the simdjson project.
- [simdjson_php](https://github.com/crazyxman/simdjson_php): PHP bindings for the simdjson project.
- [simdjson_ruby](https://github.com/saka1/simdjson_ruby): Ruby bindings for the simdjson project.
- [simdjson-go](https://github.com/minio/simdjson-go): Go port using Golang assembly.
- [rcppsimdjson](https://github.com/eddelbuettel/rcppsimdjson): R bindings.
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:
### Tools
- `json2json mydoc.json` parses the document, constructs a model and then dumps back the result to standard output.
- `json2json -d mydoc.json` parses the document, constructs a model and then dumps model (as a tape) to standard output. The tape format is described in the accompanying file `tape.md`.
- `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.
- `mkdir build`
- `cd build`
- `cmake .. -T ClangCL`
- `cmake --build . -config Release`
### 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
- [Google double-conv](https://github.com/google/double-conversion/)
- [How to implement atoi using SIMD?](https://stackoverflow.com/questions/35127060/how-to-implement-atoi-using-simd)
- [Parsing JSON is a Minefield 💣](http://seriot.ch/parsing_json.php)
- https://tools.ietf.org/html/rfc7159
- The Mison implementation in rust https://github.com/pikkr/pikkr
- http://rapidjson.org/md_doc_sax.html
- https://github.com/Geal/parser_benchmarks/tree/master/json
- Gron: A command line tool that makes JSON greppable https://news.ycombinator.com/item?id=16727665
@@ -371,31 +290,3 @@ Inspiring links:
- https://auth0.com/blog/beating-json-performance-with-protobuf/
- https://gist.github.com/shijuvar/25ad7de9505232c87034b8359543404a
- https://github.com/frankmcsherry/blog/blob/master/posts/2018-02-11.md
Validating UTF-8 takes no more than 0.7 cycles per byte:
- https://github.com/lemire/fastvalidate-utf-8 https://lemire.me/blog/2018/05/16/validating-utf-8-strings-using-as-little-as-0-7-cycles-per-byte/
### Academic References
- T.Mühlbauer, W.Rödiger, R.Seilbeck, A.Reiser, A.Kemper, and T.Neumann. Instant loading for main memory databases. PVLDB, 6(14):17021713, 2013. (SIMD-based CSV parsing)
- Mytkowicz, Todd, Madanlal Musuvathi, and Wolfram Schulte. "Data-parallel finite-state machines." ACM SIGARCH Computer Architecture News. Vol. 42. No. 1. ACM, 2014.
- Lu, Yifan, et al. "Tree structured data processing on GPUs." Cloud Computing, Data Science & Engineering-Confluence, 2017 7th International Conference on. IEEE, 2017.
- Sidhu, Reetinder. "High throughput, tree automata based XML processing using FPGAs." Field-Programmable Technology (FPT), 2013 International Conference on. IEEE, 2013.
- Dai, Zefu, Nick Ni, and Jianwen Zhu. "A 1 cycle-per-byte XML parsing accelerator." Proceedings of the 18th annual ACM/SIGDA international symposium on Field programmable gate arrays. ACM, 2010.
- Lin, Dan, et al. "Parabix: Boosting the efficiency of text processing on commodity processors." High Performance Computer Architecture (HPCA), 2012 IEEE 18th International Symposium on. IEEE, 2012. http://parabix.costar.sfu.ca/export/1783/docs/HPCA2012/final_ieee/final.pdf
- Deshmukh, V. M., and G. R. Bamnote. "An empirical evaluation of optimization parameters in XML parsing for performance enhancement." Computer, Communication and Control (IC4), 2015 International Conference on. IEEE, 2015.
- Moussalli, Roger, et al. "Efficient XML Path Filtering Using GPUs." ADMS@ VLDB. 2011.
- Jianliang, Ma, et al. "Parallel speculative dom-based XML parser." High Performance Computing and Communication & 2012 IEEE 9th International Conference on Embedded Software and Systems (HPCC-ICESS), 2012 IEEE 14th International Conference on. IEEE, 2012.
- Li, Y., Katsipoulakis, N.R., Chandramouli, B., Goldstein, J. and Kossmann, D., 2017. Mison: a fast JSON parser for data analytics. Proceedings of the VLDB Endowment, 10(10), pp.1118-1129. http://www.vldb.org/pvldb/vol10/p1118-li.pdf
- Cameron, Robert D., et al. "Parallel scanning with bitstream addition: An xml case study." European Conference on Parallel Processing. Springer, Berlin, Heidelberg, 2011.
- Cameron, Robert D., Kenneth S. Herdy, and Dan Lin. "High performance XML parsing using parallel bit stream technology." Proceedings of the 2008 conference of the center for advanced studies on collaborative research: meeting of minds. ACM, 2008.
- Shah, Bhavik, et al. "A data parallel algorithm for XML DOM parsing." International XML Database Symposium. Springer, Berlin, Heidelberg, 2009.
- Cameron, Robert D., and Dan Lin. "Architectural support for SWAR text processing with parallel bit streams: the inductive doubling principle." ACM Sigplan Notices. Vol. 44. No. 3. ACM, 2009.
- Amagasa, Toshiyuki, Mana Seino, and Hiroyuki Kitagawa. "Energy-Efficient XML Stream Processing through Element-Skipping Parsing." Database and Expert Systems Applications (DEXA), 2013 24th International Workshop on. IEEE, 2013.
- Medforth, Nigel Woodland. "icXML: Accelerating Xerces-C 3.1. 1 using the Parabix Framework." (2013).
- Zhang, Qiang Scott. Embedding Parallel Bit Stream Technology Into Expat. Diss. Simon Fraser University, 2010.
- Cameron, Robert D., et al. "Fast Regular Expression Matching with Bit-parallel Data Streams."
- Lin, Dan. Bits filter: a high-performance multiple string pattern matching algorithm for malware detection. Diss. School of Computing Science-Simon Fraser University, 2010.
- Yang, Shiyang. Validation of XML Document Based on Parallel Bit Stream Technology. Diss. Applied Sciences: School of Computing Science, 2013.
- N. Nakasato, "Implementation of a parallel tree method on a GPU", Journal of Computational Science, vol. 3, no. 3, pp. 132-141, 2012.
-301
View File
@@ -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
+19 -13
View File
@@ -1,8 +1,9 @@
[![Build Status](https://cloud.drone.io/api/badges/simdjson/simdjson/status.svg)](https://cloud.drone.io/simdjson/simdjson)
[![CircleCI](https://circleci.com/gh/simdjson/simdjson.svg?style=svg)](https://circleci.com/gh/simdjson/simdjson)
[![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/simdjson.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&q=proj%3Asimdjson&can=2)
[![Build status](https://ci.appveyor.com/api/projects/status/ae77wp5v3lebmu6n/branch/master?svg=true)](https://ci.appveyor.com/project/lemire/simdjson-jmmti/branch/master)
[![][license img]][license]
![Ubuntu 18.04 CI](https://github.com/simdjson/simdjson/workflows/Ubuntu%2018.04%20CI%20(GCC%207)/badge.svg)
[![Ubuntu 20.04 CI](https://github.com/simdjson/simdjson/workflows/Ubuntu%2020.04%20CI%20(GCC%209)/badge.svg)](https://simdjson.org/plots.html)
![VS16-CI](https://github.com/simdjson/simdjson/workflows/VS16-CI/badge.svg)
![MinGW64-CI](https://github.com/simdjson/simdjson/workflows/MinGW64-CI/badge.svg)
[![][license img]][license] [![Doxygen Documentation](https://img.shields.io/badge/docs-doxygen-green.svg)](https://simdjson.org/api/0.5.0/index.html)
simdjson : Parsing gigabytes of JSON per second
===============================================
@@ -39,7 +40,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 +55,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 +70,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.5.0/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
@@ -128,6 +128,7 @@ Real-world usage
- [Microsoft FishStore](https://github.com/microsoft/FishStore)
- [Yandex ClickHouse](https://github.com/yandex/ClickHouse)
- [Clang Build Analyzer](https://github.com/aras-p/ClangBuildAnalyzer)
- [Shopify HeapProfiler](https://github.com/Shopify/heap-profiler)
If you are planning to use simdjson in a product, please work from one of our releases.
@@ -137,6 +138,7 @@ Bindings and Ports of simdjson
We distinguish between "bindings" (which just wrap the C++ code) and a port to another programming language (which reimplements everything).
- [ZippyJSON](https://github.com/michaeleisel/zippyjson): Swift bindings for the simdjson project.
- [libpy_simdjson](https://github.com/gerrymanoim/libpy_simdjson/): high-speed Python bindings for simdjson using [libpy](https://github.com/quantopian/libpy).
- [pysimdjson](https://github.com/TkTech/pysimdjson): Python bindings for the simdjson project.
- [simdjson-rs](https://github.com/simd-lite): Rust port.
- [simdjson-rust](https://github.com/SunDoge/simdjson-rust): Rust wrapper (bindings).
@@ -144,6 +146,7 @@ We distinguish between "bindings" (which just wrap the C++ code) and a port to a
- [simdjson_nodejs](https://github.com/luizperes/simdjson_nodejs): Node.js bindings for the simdjson project.
- [simdjson_php](https://github.com/crazyxman/simdjson_php): PHP bindings for the simdjson project.
- [simdjson_ruby](https://github.com/saka1/simdjson_ruby): Ruby bindings for the simdjson project.
- [fast_jsonparser](https://github.com/anilmaurya/fast_jsonparser): Ruby bindings for the simdjson project.
- [simdjson-go](https://github.com/minio/simdjson-go): Go port using Golang assembly.
- [rcppsimdjson](https://github.com/eddelbuettel/rcppsimdjson): R bindings.
@@ -167,7 +170,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 +185,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.
+36
View File
@@ -1,3 +1,39 @@
# 0.5
## Highlights
Performance
* Faster and simpler UTF-8 validation with the lookup4 algorithm https://github.com/simdjson/simdjson/pull/993
* We improved the performance of simdjson under Visual Studio by about 25%. Users will still get better performance with clang-cl (+30%) but the gap has been reduced. https://github.com/simdjson/simdjson/pull/1031
Code usability
* In `parse_many`, when parsing streams of JSON documetns, we give to the users runtime control as to whether threads are used (via the parser.threaded attribute). https://github.com/simdjson/simdjson/issues/925
* Prefixed public macros to avoid name clashes with other libraries. https://github.com/simdjson/simdjson/issues/1035
* Better documentation regarding package managers (brew, MSYS2, conan, apt, vcpkg, FreeBSD package manager, etc.).
* Better documentation regarding CMake usage.
Standards
* We improved standard compliance with respect to both the JSON RFC 8259 and JSON Pointer RFC 6901. We added the at_pointer method to nodes for standard-compliant JSON Pointer queries. The legacy `at(std::string_view)` method remains but is deprecated since it is not standard-compliant as per RFC 6901.
* We removed computed GOTOs without sacrificing performance thus improving the C++ standard compliance (since computed GOTOs are compiler-specific extensions).
* Better support for C++20 https://github.com/simdjson/simdjson/pull/1050
# 0.4
## 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
-185
View File
@@ -1,185 +0,0 @@
#!/bin/bash
########################################################################
# Generates an "amalgamation build" for roaring. Inspired by similar
# script used by whefs.
########################################################################
SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
echo "We are about to amalgamate all simdjson files into one source file. "
echo "See https://www.sqlite.org/amalgamation.html and https://en.wikipedia.org/wiki/Single_Compilation_Unit for rationale. "
AMAL_H="simdjson.h"
AMAL_C="simdjson.cpp"
SRCPATH="$SCRIPTPATH/src"
INCLUDEPATH="$SCRIPTPATH/include"
# this list excludes the "src/generic headers"
ALLCFILES="
simdjson.cpp
"
# order matters
ALLCHEADERS="
simdjson.h
"
found_includes=()
for file in ${ALLCFILES}; do
test -e "$SRCPATH/$file" && continue
echo "FATAL: source file [$SRCPATH/$file] not found."
exit 127
done
for file in ${ALLCHEADERS}; do
test -e "$INCLUDEPATH/$file" && continue
echo "FATAL: source file [$INCLUDEPATH/$file] not found."
exit 127
done
function doinclude()
{
file=$1
line="${@:2}"
if [ -f $INCLUDEPATH/$file ]; then
if [[ ! " ${found_includes[@]} " =~ " ${file} " ]]; then
found_includes+=("$file")
dofile $INCLUDEPATH/$file
fi;
elif [ -f $SRCPATH/$file ]; then
# generic includes are included multiple times
if [[ "${file}" == *'generic/'*'.h' ]]; then
dofile $SRCPATH/$file
elif [[ ! " ${found_includes[@]} " =~ " ${file} " ]]; then
found_includes+=("$file")
dofile $SRCPATH/$file
else
echo "/* $file already included: $line */"
fi
else
# If we don't recognize it, just emit the #include
echo "$line"
fi
}
function dofile()
{
# Last lines are always ignored. Files should end by an empty lines.
RELFILE=${1#"$SCRIPTPATH/"}
echo "/* begin file $RELFILE */"
# echo "#line 8 \"$1\"" ## redefining the line/file is not nearly as useful as it sounds for debugging. It breaks IDEs.
while IFS= read -r line || [ -n "$line" ];
do
if [[ "${line}" == '#include "'*'"'* ]]; then
file=$(echo $line| cut -d'"' -f 2)
if [[ "${file}" == '../'* ]]; then
file=$(echo $file| cut -d'/' -f 2-)
fi;
# we explicitly include simdjson headers, one time each (unless they are generic, in which case multiple times is fine)
doinclude $file $line
else
# Otherwise we simply copy the line
echo "$line"
fi
done < "$1"
echo "/* end file $RELFILE */"
}
timestamp=$(date)
echo "Creating ${AMAL_H}..."
echo "/* auto-generated on ${timestamp}. Do not edit! */" > "${AMAL_H}"
{
for h in ${ALLCHEADERS}; do
doinclude $h "ERROR $h not found"
done
} >> "${AMAL_H}"
echo "Creating ${AMAL_C}..."
echo "/* auto-generated on ${timestamp}. Do not edit! */" > "${AMAL_C}"
{
echo "#include \"${AMAL_H}\""
echo ""
echo "/* used for http://dmalloc.com/ Dmalloc - Debug Malloc Library */"
echo "#ifdef DMALLOC"
echo "#include \"dmalloc.h\""
echo "#endif"
echo ""
for file in ${ALLCFILES}; do
dofile "$SRCPATH/$file"
done
} >> "${AMAL_C}"
DEMOCPP="amalgamation_demo.cpp"
echo "Creating ${DEMOCPP}..."
echo "/* auto-generated on ${timestamp}. Do not edit! */" > "${DEMOCPP}"
cat <<< '
#include <iostream>
#include "simdjson.h"
#include "simdjson.cpp"
int main(int argc, char *argv[]) {
if(argc < 2) {
std::cerr << "Please specify at least one file name. " << std::endl;
}
const char * filename = argv[1];
simdjson::dom::parser parser;
auto [doc, error] = parser.load(filename); // do the parsing
if (error) {
std::cout << "parse failed" << std::endl;
std::cout << "error code: " << error << std::endl;
std::cout << error << std::endl;
} else {
std::cout << "parse valid" << std::endl;
}
if(argc == 2) {
return EXIT_SUCCESS;
}
// parse_many
const char * filename2 = argv[2];
for (auto result : parser.load_many(filename2)) {
error = result.error();
}
if (error) {
std::cout << "parse_many failed" << std::endl;
std::cout << "error code: " << error << std::endl;
std::cout << error << std::endl;
} else {
std::cout << "parse_many valid" << std::endl;
}
return EXIT_SUCCESS;
}
' >> "${DEMOCPP}"
echo "Done with all files generation. "
echo "Files have been written to directory: $PWD "
ls -la ${AMAL_C} ${AMAL_H} ${DEMOCPP}
echo "Giving final instructions:"
CPPBIN=${DEMOCPP%%.*}
echo "Try :"
echo "c++ -O3 -std=c++17 -pthread -o ${CPPBIN} ${DEMOCPP} && ./${CPPBIN} ../jsonexamples/twitter.json ../jsonexamples/amazon_cellphones.ndjson"
SINGLEHDR=$SCRIPTPATH/singleheader
echo "Copying files to $SCRIPTPATH/singleheader "
mkdir -p $SINGLEHDR
echo "c++ -O3 -std=c++17 -pthread -o ${CPPBIN} ${DEMOCPP} && ./${CPPBIN} ../jsonexamples/twitter.json ../jsonexamples/amazon_cellphones.ndjson" > $SINGLEHDR/README.md
cp ${AMAL_C} ${AMAL_H} ${DEMOCPP} $SINGLEHDR
ls $SINGLEHDR
cd $SINGLEHDR && c++ -O3 -std=c++17 -pthread -o ${CPPBIN} ${DEMOCPP} && ./${CPPBIN} ../jsonexamples/twitter.json ../jsonexamples/amazon_cellphones.ndjson
lowercase(){
echo "$1" | tr 'A-Z' 'a-z'
}
OS=`lowercase \`uname\``
+41 -17
View File
@@ -1,21 +1,45 @@
target_include_directories(${SIMDJSON_LIB_NAME}
INTERFACE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/benchmark>
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/benchmark/linux>
)
include_directories( . linux )
link_libraries(simdjson-windows-headers test-data)
add_cpp_benchmark(parse)
add_cpp_benchmark(statisticalmodel)
add_cpp_benchmark(parse_stream)
add_cpp_benchmark(get_corpus_benchmark)
if (TARGET benchmark::benchmark)
add_executable(bench_sax bench_sax.cpp)
target_link_libraries(bench_sax simdjson-internal-flags simdjson-include-source benchmark::benchmark)
endif (TARGET benchmark::benchmark)
link_libraries(simdjson simdjson-flags)
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 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()
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()
include(checkperf.cmake)
+401 -57
View File
@@ -6,19 +6,346 @@ 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 recover_one_string(State& state) {
dom::parser parser;
const std::string_view data = "\"one string\"";
padded_string docdata{data};
// we do not want mem. alloc. in the loop.
auto error = parser.allocate(docdata.size());
if(error) {
cout << error << endl;
return;
}
dom::element doc;
if ((error = parser.parse(docdata).get(doc))) {
cerr << "could not parse string" << error << endl;
return;
}
for (SIMDJSON_UNUSED auto _ : state) {
std::string_view v;
error = doc.get(v);
if (error) {
cerr << "could not get string" << error << endl;
return;
}
benchmark::DoNotOptimize(v);
}
}
BENCHMARK(recover_one_string);
static void serialize_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.
if((error = parser.allocate(docdata.size()))) {
cout << error << endl;
return;
}
dom::element doc;
if ((error = parser.parse(docdata).get(doc))) {
cerr << "could not parse twitter.json" << error << endl;
return;
}
size_t bytes = 0;
for (SIMDJSON_UNUSED auto _ : state) {
std::string serial = simdjson::minify(doc);
bytes += serial.size();
benchmark::DoNotOptimize(serial);
}
// 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(serialize_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 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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_UNUSED auto _ : state) {
uint64_t result_count = doc["search_metadata"]["count"];
if (result_count != 100) { return; }
}
@@ -29,9 +356,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 (SIMDJSON_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 +375,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 (SIMDJSON_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 +392,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 (SIMDJSON_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 +416,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 (SIMDJSON_UNUSED auto _ : state) {
uint64_t value;
if ((error = doc["search_metadata"]["count"].get(value))) { return; }
if (value != 100) { return; }
}
}
@@ -100,20 +430,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 (SIMDJSON_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 +459,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 (SIMDJSON_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 +501,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 (SIMDJSON_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 +532,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 (SIMDJSON_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 +593,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 (SIMDJSON_UNUSED auto _ : state) {
std::stringstream s;
if (!parser.print_json(s)) { cerr << "print_json failed" << endl; return; }
}
+129 -11
View File
@@ -5,13 +5,118 @@ 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 unicode_validate_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 (SIMDJSON_UNUSED auto _ : state) {
bool is_ok = simdjson::validate_utf8(docdata.data(), docdata.size());
bytes += docdata.size();
benchmark::DoNotOptimize(is_ok);
}
// 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(unicode_validate_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_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_UNUSED auto _ : state) {
auto error = json_parse(EMPTY_ARRAY, pj);
if (error) { return; }
}
@@ -21,53 +126,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 (SIMDJSON_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 (SIMDJSON_UNUSED auto _ : state) {
try {
UNUSED dom::element doc = parser.parse(EMPTY_ARRAY);
SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_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 (SIMDJSON_UNUSED auto _ : state) {
try {
dom::parser parser;
UNUSED dom::element doc = parser.parse(EMPTY_ARRAY);
SIMDJSON_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();
+359
View File
@@ -0,0 +1,359 @@
#define SIMDJSON_IMPLEMENTATION_FALLBACK 0
#define SIMDJSON_IMPLEMENTATION_WESTMERE 0
#define SIMDJSON_IMPLEMENTATION_AMD64 0
#include <iostream>
#include <sstream>
#include <random>
#include "simdjson.h"
SIMDJSON_PUSH_DISABLE_ALL_WARNINGS
#include <benchmark/benchmark.h>
SIMDJSON_POP_DISABLE_WARNINGS
#include "simdjson.cpp"
#if SIMDJSON_EXCEPTIONS
using namespace benchmark;
using namespace simdjson;
using std::cerr;
using std::endl;
const char *TWITTER_JSON = SIMDJSON_BENCHMARK_DATA_DIR "twitter.json";
const int REPETITIONS = 10;
#if SIMDJSON_IMPLEMENTATION_HASWELL
#include "twitter/sax_tweet_reader.h"
static void sax_tweets(State &state) {
// Load twitter.json to a buffer
padded_string json;
if (auto error = padded_string::load(TWITTER_JSON).get(json)) { cerr << error << endl; return; }
// Allocate
twitter::sax_tweet_reader reader;
if (auto error = reader.set_capacity(json.size())) { cerr << error << endl; return; }
// Warm the vector
if (auto error = reader.read_tweets(json)) { throw error; }
// Read tweets
size_t bytes = 0;
size_t tweets = 0;
for (SIMDJSON_UNUSED auto _ : state) {
if (auto error = reader.read_tweets(json)) { throw error; }
bytes += json.size();
tweets += reader.tweets.size();
}
// 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);
state.counters["tweets"] = Counter(double(tweets), benchmark::Counter::kIsRate);
}
BENCHMARK(sax_tweets)->Repetitions(REPETITIONS)->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
return *(std::max_element(std::begin(v), std::end(v)));
})->DisplayAggregatesOnly(true);
#endif // SIMDJSON_IMPLEMENTATION_HASWELL
#include "twitter/tweet.h"
simdjson_really_inline uint64_t nullable_int(dom::element element) {
if (element.is_null()) { return 0; }
return element;
}
simdjson_really_inline void read_dom_tweets(dom::parser &parser, padded_string &json, std::vector<twitter::tweet> &tweets) {
for (dom::element tweet : parser.parse(json)["statuses"]) {
auto user = tweet["user"];
tweets.push_back(
{
tweet["id"],
tweet["text"],
tweet["created_at"],
nullable_int(tweet["in_reply_to_status_id"]),
tweet["retweet_count"],
tweet["favorite_count"],
{ user["id"], user["screen_name"] }
}
);
}
}
static void dom_tweets(State &state) {
// Load twitter.json to a buffer
padded_string json;
if (auto error = padded_string::load(TWITTER_JSON).get(json)) { cerr << error << endl; return; }
// Allocate
dom::parser parser;
if (auto error = parser.allocate(json.size())) { cerr << error << endl; return; };
// Warm the vector
std::vector<twitter::tweet> tweets;
read_dom_tweets(parser, json, tweets);
// Read tweets
size_t bytes = 0;
size_t num_tweets = 0;
for (SIMDJSON_UNUSED auto _ : state) {
tweets.clear();
read_dom_tweets(parser, json, tweets);
bytes += json.size();
num_tweets += tweets.size();
}
// 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);
state.counters["tweets"] = Counter(double(num_tweets), benchmark::Counter::kIsRate);
}
BENCHMARK(dom_tweets)->Repetitions(REPETITIONS)->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
return *(std::max_element(std::begin(v), std::end(v)));
})->DisplayAggregatesOnly(true);
static void dom_parse(State &state) {
// Load twitter.json to a buffer
padded_string json;
if (auto error = padded_string::load(TWITTER_JSON).get(json)) { cerr << error << endl; return; }
// Allocate
dom::parser parser;
if (auto error = parser.allocate(json.size())) { cerr << error << endl; return; };
// Read tweets
size_t bytes = 0;
for (SIMDJSON_UNUSED auto _ : state) {
if (parser.parse(json).error()) { throw "Parsing failed"; };
bytes += json.size();
}
// 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(dom_parse)->Repetitions(REPETITIONS)->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
return *(std::max_element(std::begin(v), std::end(v)));
})->DisplayAggregatesOnly(true);
/********************
* Large file parsing benchmarks:
********************/
static std::string build_json_array(size_t N) {
std::default_random_engine e;
std::uniform_real_distribution<> dis(0, 1);
std::stringstream myss;
myss << "[" << std::endl;
if(N > 0) {
myss << "{ \"x\":" << dis(e) << ", \"y\":" << dis(e) << ", \"z\":" << dis(e) << "}" << std::endl;
}
for(size_t i = 1; i < N; i++) {
myss << "," << std::endl;
myss << "{ \"x\":" << dis(e) << ", \"y\":" << dis(e) << ", \"z\":" << dis(e) << "}";
}
myss << std::endl;
myss << "]" << std::endl;
std::string answer = myss.str();
std::cout << "Creating a source file spanning " << (answer.size() + 512) / 1024 << " KB " << std::endl;
return answer;
}
static const simdjson::padded_string& get_my_json_str() {
static simdjson::padded_string s = build_json_array(1000000);
return s;
}
struct my_point {
double x;
double y;
double z;
};
// ./benchmark/bench_sax --benchmark_filter=largerandom
/***
* We start with the naive DOM-based approach.
**/
static void dom_parse_largerandom(State &state) {
// Load twitter.json to a buffer
const padded_string& json = get_my_json_str();
// Allocate
dom::parser parser;
if (auto error = parser.allocate(json.size())) { cerr << error << endl; return; };
// Read
size_t bytes = 0;
simdjson::error_code error;
for (SIMDJSON_UNUSED auto _ : state) {
std::vector<my_point> container;
dom::element doc;
if ((error = parser.parse(json).get(doc))) {
std::cerr << "failure: " << error << std::endl;
throw "Parsing failed";
};
for (auto p : doc) {
container.emplace_back(my_point{p["x"], p["y"], p["z"]});
}
bytes += json.size();
benchmark::DoNotOptimize(container.data());
}
// 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(dom_parse_largerandom)->Repetitions(REPETITIONS)->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
return *(std::max_element(std::begin(v), std::end(v)));
})->DisplayAggregatesOnly(true);
#if SIMDJSON_IMPLEMENTATION_HASWELL
/***
* Next we are going to code the SAX approach.
**/
SIMDJSON_TARGET_HASWELL
namespace largerandom {
namespace {
using namespace simdjson;
using namespace haswell;
using namespace haswell::stage2;
struct sax_point_reader_visitor {
public:
sax_point_reader_visitor(std::vector<my_point> &_points) : points(_points) {
}
simdjson_really_inline error_code visit_document_start(json_iterator &) { return SUCCESS; }
simdjson_really_inline error_code visit_object_start(json_iterator &) { return SUCCESS; }
simdjson_really_inline error_code visit_key(json_iterator &, const uint8_t *key) {
switch(key[0]) {
case 'x':
idx = 0;
break;
case 'y':
idx = 2;
break;
case 'z':
idx = 3;
break;
}
return SUCCESS;
}
simdjson_really_inline error_code visit_primitive(json_iterator &, const uint8_t *value) {
return numberparsing::parse_double(value).get(buffer[idx]);
}
simdjson_really_inline error_code visit_array_start(json_iterator &) { return SUCCESS; }
simdjson_really_inline error_code visit_array_end(json_iterator &) { return SUCCESS; }
simdjson_really_inline error_code visit_object_end(json_iterator &) { return SUCCESS; }
simdjson_really_inline error_code visit_document_end(json_iterator &) { return SUCCESS; }
simdjson_really_inline error_code visit_empty_array(json_iterator &) { return SUCCESS; }
simdjson_really_inline error_code visit_empty_object(json_iterator &) { return SUCCESS; }
simdjson_really_inline error_code visit_root_primitive(json_iterator &, const uint8_t *) { return SUCCESS; }
simdjson_really_inline error_code increment_count(json_iterator &) { return SUCCESS; }
std::vector<my_point> &points;
size_t idx{0};
double buffer[3];
};
struct sax_point_reader {
std::vector<my_point> points;
std::unique_ptr<uint8_t[]> string_buf;
size_t capacity;
dom_parser_implementation dom_parser;
sax_point_reader();
error_code set_capacity(size_t new_capacity);
error_code read_points(const padded_string &json);
}; // struct sax_point_reader
sax_point_reader::sax_point_reader() : points{}, string_buf{}, capacity{0}, dom_parser() {
}
error_code sax_point_reader::set_capacity(size_t new_capacity) {
// string_capacity copied from document::allocate
size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * new_capacity / 3 + 32, 64);
string_buf.reset(new (std::nothrow) uint8_t[string_capacity]);
if (auto error = dom_parser.set_capacity(new_capacity)) { return error; }
if (capacity == 0) { // set max depth the first time only
if (auto error = dom_parser.set_max_depth(DEFAULT_MAX_DEPTH)) { return error; }
}
capacity = new_capacity;
return SUCCESS;
}
error_code sax_point_reader::read_points(const padded_string &json) {
// Allocate capacity if needed
points.clear();
if (capacity < json.size()) {
if (auto error = set_capacity(capacity)) { return error; }
}
// Run stage 1 first.
if (auto error = dom_parser.stage1((uint8_t *)json.data(), json.size(), false)) { return error; }
// Then walk the document, parsing the tweets as we go
json_iterator iter(dom_parser, 0);
sax_point_reader_visitor visitor(points);
if (auto error = iter.walk_document<false>(visitor)) { return error; }
return SUCCESS;
}
} // unnamed namespace
} // namespace largerandom
SIMDJSON_UNTARGET_REGION
// ./benchmark/bench_sax --benchmark_filter=largerandom
static void sax_parse_largerandom(State &state) {
// Load twitter.json to a buffer
const padded_string& json = get_my_json_str();
// Allocate
largerandom::sax_point_reader reader;
if (auto error = reader.set_capacity(json.size())) { throw error; }
// warming
for(size_t i = 0; i < 10; i++) {
if (auto error = reader.read_points(json)) { throw error; }
}
// Read
size_t bytes = 0;
for (SIMDJSON_UNUSED auto _ : state) {
if (auto error = reader.read_points(json)) { throw error; }
bytes += json.size();
benchmark::DoNotOptimize(reader.points.data());
}
// 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(sax_parse_largerandom)->Repetitions(REPETITIONS)->ComputeStatistics("max", [](const std::vector<double>& v) -> double {
return *(std::max_element(std::begin(v), std::end(v)));
})->DisplayAggregatesOnly(true);
#endif // SIMDJSON_IMPLEMENTATION_HASWELL
#endif // SIMDJSON_EXCEPTIONS
BENCHMARK_MAIN();
+75 -89
View File
@@ -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,25 +140,25 @@ 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)
{
}
really_inline void run_iterations(size_t iterations, bool stage1_only=false) {
simdjson_really_inline void run_iterations(size_t iterations, bool stage1_only=false) {
struct7.run_iterations(iterations, stage1_only);
struct7_miss.run_iterations(iterations, stage1_only);
struct7_full.run_iterations(iterations, stage1_only);
@@ -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 -185
View File
@@ -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,47 @@ 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; \
} \
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 "); \
} \
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); \
printf("\n"); \
fflush(NULL); \
} while (0)
@@ -149,78 +59,45 @@ 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)
+99 -71
View File
@@ -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++;
}
@@ -222,8 +225,19 @@ struct progress_bar {
}
};
/**
* The speed at which we can allocate memory is strictly system specific.
* It depends on the OS and the runtime library. It is subject to various
* system-specific knobs. It is not something that we can reasonably
* benchmark with crude timings.
* If someone wants to optimize how simdjson allocate memory, then it will
* almost surely require a distinct benchmarking tool. What is meant by
* "memory allocation" also requires a definition. Doing "new char[size]" can
* do many different things depending on the system.
*/
enum class BenchmarkStage {
ALL,
ALL, // This excludes allocation
ALLOCATE,
STAGE1,
STAGE2
@@ -231,7 +245,7 @@ enum class BenchmarkStage {
const char* benchmark_stage_name(BenchmarkStage stage) {
switch (stage) {
case BenchmarkStage::ALL: return "All";
case BenchmarkStage::ALL: return "All (Without Allocation)";
case BenchmarkStage::ALLOCATE: return "Allocate";
case BenchmarkStage::STAGE1: return "Stage 1";
case BenchmarkStage::STAGE2: return "Stage 2";
@@ -241,7 +255,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 +264,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 (stage 1 and stage 2, but *excluding* allocation)
event_aggregate all_stages_without_allocation{};
// 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,25 +291,29 @@ 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;
case BenchmarkStage::ALL: return this->all_stages_without_allocation;
case BenchmarkStage::STAGE1: return this->stage1;
case BenchmarkStage::STAGE2: return this->stage2;
case BenchmarkStage::ALLOCATE: return this->allocate_stage;
default: exit_error("Unknown stage"); return this->all_stages;
default: exit_error("Unknown stage"); return this->all_stages_without_allocation;
}
}
int iterations() const {
return all_stages.iterations;
return all_stages_without_allocation.iterations;
}
really_inline void run_iteration(bool stage1_only, bool hotbuffers=false) {
simdjson_really_inline void run_iteration(bool stage1_only, bool hotbuffers=false) {
// Allocate dom::parser
collector.start();
dom::parser parser;
error_code error = parser.allocate(json.size());
// We always allocate at least 64KB. Smaller allocations may actually be slower under some systems.
error_code error = parser.allocate(json.size() < 65536 ? 65536 : json.size());
if (error) {
exit_error(string("Unable to allocate_stage ") + to_string(json.size()) + " bytes for the JSON result: " + error_message(error));
}
@@ -314,7 +331,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) {
@@ -324,22 +341,22 @@ struct benchmarker {
// Stage 2 (unified machine) and the rest
if (stage1_only) {
all_stages << stage1_count;
all_stages_without_allocation << stage1_count;
} 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));
}
stage2_count = collector.end();
stage2 << stage2_count;
all_stages << allocate_count + stage1_count + stage2_count;
all_stages_without_allocation << stage1_count + stage2_count;
}
// 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");
}
@@ -367,43 +384,44 @@ struct benchmarker {
loop << all_loop_count;
}
really_inline void run_iterations(size_t iterations, bool stage1_only, bool hotbuffers=false) {
simdjson_really_inline void run_iterations(size_t iterations, bool stage1_only, bool hotbuffers=false) {
for (size_t i = 0; i<iterations; i++) {
run_iteration(stage1_only, hotbuffers);
}
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_without_allocation.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_without_allocation.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_without_allocation.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 +429,29 @@ struct benchmarker {
prefix,
"Misses",
stage.branch_misses(),
100.0 * stage.branch_misses() / all_stages.branch_misses(),
percent(stage.branch_misses(), all_stages_without_allocation.branch_misses()),
stage.cache_misses(),
100.0 * stage.cache_misses() / all_stages.cache_misses(),
percent(stage.cache_misses(), all_stages_without_allocation.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,21 +461,21 @@ 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(),
gb / all_stages.best.elapsed_sec(),
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_without_allocation.best.cycles() / static_cast<double>(json.size()),
gb / all_stages_without_allocation.best.elapsed_sec(),
gb / stage1.best.elapsed_sec(),
gb / stage2.best.elapsed_sec());
} else {
printf("\"%s\"\t\t\t\t\t%f\t%f\t%f\n",
base,
gb / all_stages.best.elapsed_sec(),
gb / all_stages_without_allocation.best.elapsed_sec(),
gb / stage1.best.elapsed_sec(),
gb / stage2.best.elapsed_sec());
}
@@ -455,28 +484,28 @@ 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");
print_aggregate("| " , all_stages.best);
printf("All Stages (excluding allocation)\n");
print_aggregate("| " , all_stages_without_allocation.best);
// frequently, allocation is a tiny fraction of the running time so we omit it
if(allocate_stage.best.elapsed_sec() > 0.01 * all_stages.best.elapsed_sec()) {
if(allocate_stage.best.elapsed_sec() > 0.01 * all_stages_without_allocation.best.elapsed_sec()) {
printf("|- Allocation\n");
print_aggregate("| ", allocate_stage.best);
}
@@ -487,17 +516,16 @@ struct benchmarker {
if (collector.has_events()) {
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 freqall = (all_stages_without_allocation.best.cycles() / all_stages_without_allocation.best.elapsed_sec()) / 1000000000.0;
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"
"Range for stage 1 and stage 2 : [%.3f GHz, %.3f GHz], overall: %.3f GHz.\n",
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_without_allocation.best.elapsed_sec()));
}
}
};
+101
View File
@@ -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 SIMDJSON_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 ()
+67 -53
View File
@@ -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>());
}
simdjson_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);
}
}
}
simdjson_really_inline void simdjson_recurse(std::vector<int64_t> & v, simdjson::dom::element element) {
SIMDJSON_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>
simdjson_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>
simdjson_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
simdjson_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>
simdjson_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>
simdjson_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
simdjson_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>
simdjson_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>
simdjson_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
simdjson_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);
+14 -14
View File
@@ -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;
@@ -133,13 +133,13 @@ struct event_collector {
}
#endif
really_inline void start() {
simdjson_really_inline void start() {
#if defined(__linux)
linux_events.start();
#endif
start_clock = steady_clock::now();
}
really_inline event_count& end() {
simdjson_really_inline event_count& end() {
time_point<steady_clock> end_clock = steady_clock::now();
#if defined(__linux)
linux_events.end(count.event_counts);
@@ -149,4 +149,4 @@ struct event_collector {
}
};
#endif
#endif
+6 -5
View File
@@ -4,7 +4,8 @@
#include <cstring>
#include <iostream>
never_inline
// Gigabyte: https://en.wikipedia.org/wiki/Gigabyte
simdjson_never_inline
double bench(std::string filename, simdjson::padded_string& p) {
std::chrono::time_point<std::chrono::steady_clock> start_clock =
std::chrono::steady_clock::now();
@@ -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;
+5 -5
View File
@@ -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");
}
+32 -10
View File
@@ -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,27 +75,33 @@ 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;
}
char *buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
if(buffer == nullptr) {
std::cerr << "Out of memory!" << std::endl;
abort();
}
memcpy(buffer, p.data(), p.size());
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 +116,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?
@@ -124,9 +143,12 @@ int main(int argc, char *argv[]) {
!just_data);
char *mini_buffer = simdjson::internal::allocate_padded_buffer(p.size() + 1);
if(mini_buffer == nullptr) {
std::cerr << "Out of memory" << std::endl;
abort();
}
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
View File
@@ -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
View File
@@ -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;
}
+173 -30
View File
@@ -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_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) {
simdjson_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,115 @@ 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, kv.value);
stat.stringLength += kv.key.size();
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;
}
}
simdjson_never_inline Stat rapidjson_compute_stats_ref(const rapidjson::Value &doc) {
Stat s{};
RapidGenStat(s, doc);
return s;
}
simdjson_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 +268,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;
simdjson_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 +329,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;
simdjson_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 +355,9 @@ rapid_compute_stats(const simdjson::padded_string &p) {
return answer;
}
__attribute__((noinline)) stat_t
simdjson_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 +411,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 +451,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 +459,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);
}
}
+51 -38
View File
@@ -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__
@@ -53,7 +53,7 @@ using namespace rapidjson;
#ifdef ALLPARSER
// fastjson has a tricky interface
void on_json_error(void *, UNUSED const fastjson::ErrorContext &ec) {
void on_json_error(void *, SIMDJSON_UNUSED const fastjson::ErrorContext &ec) {
// std::cerr<<"ERROR: "<<ec.mesg<<std::endl;
}
bool fastjson_parse(const char *input) {
@@ -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);
simdjson_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
View File
@@ -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);
}
+23 -18
View File
@@ -1,7 +1,5 @@
#include <iostream>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include "simdjson.h"
#ifdef __linux__
#include "linux-perf-events.h"
@@ -43,7 +41,7 @@ using stat_t = struct stat_s;
really_inline void simdjson_process_atom(stat_t &s,
simdjson_really_inline void simdjson_process_atom(stat_t &s,
simdjson::dom::element element) {
if (element.is<int64_t>()) {
s.integer_count++;
@@ -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;
+67
View File
@@ -0,0 +1,67 @@
#ifndef TWITTER_SAX_TWEET_READER_H
#define TWITTER_SAX_TWEET_READER_H
#include "simdjson.h"
#include "sax_tweet_reader_visitor.h"
#include "tweet.h"
#include <vector>
SIMDJSON_TARGET_HASWELL
namespace twitter {
namespace {
using namespace simdjson;
using namespace haswell;
using namespace haswell::stage2;
struct sax_tweet_reader {
std::vector<tweet> tweets;
std::unique_ptr<uint8_t[]> string_buf;
size_t capacity;
dom_parser_implementation dom_parser;
sax_tweet_reader();
error_code set_capacity(size_t new_capacity);
error_code read_tweets(padded_string &json);
}; // struct tweet_reader
sax_tweet_reader::sax_tweet_reader() : tweets{}, string_buf{}, capacity{0}, dom_parser() {
}
error_code sax_tweet_reader::set_capacity(size_t new_capacity) {
// string_capacity copied from document::allocate
size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * new_capacity / 3 + 32, 64);
string_buf.reset(new (std::nothrow) uint8_t[string_capacity]);
if (auto error = dom_parser.set_capacity(new_capacity)) { return error; }
if (capacity == 0) { // set max depth the first time only
if (auto error = dom_parser.set_max_depth(DEFAULT_MAX_DEPTH)) { return error; }
}
capacity = new_capacity;
return SUCCESS;
}
// NOTE: this assumes the dom_parser is already allocated
error_code sax_tweet_reader::read_tweets(padded_string &json) {
// Allocate capacity if needed
tweets.clear();
if (capacity < json.size()) {
if (auto error = set_capacity(capacity)) { return error; }
}
// Run stage 1 first.
if (auto error = dom_parser.stage1((uint8_t *)json.data(), json.size(), false)) { return error; }
// Then walk the document, parsing the tweets as we go
json_iterator iter(dom_parser, 0);
sax_tweet_reader_visitor visitor(tweets, string_buf.get());
if (auto error = iter.walk_document<false>(visitor)) { return error; }
return SUCCESS;
}
} // unnamed namespace
} // namespace twitter
SIMDJSON_UNTARGET_REGION
#endif // TWITTER_SAX_TWEET_READER_H
@@ -0,0 +1,519 @@
#ifndef TWITTER_SAX_TWEET_READER_VISITOR_H
#define TWITTER_SAX_TWEET_READER_VISITOR_H
#include "simdjson.h"
#include "tweet.h"
#include <vector>
SIMDJSON_TARGET_HASWELL
namespace twitter {
using namespace simdjson;
using namespace haswell;
using namespace haswell::stage2;
struct sax_tweet_reader_visitor {
public:
sax_tweet_reader_visitor(std::vector<tweet> &_tweets, uint8_t *string_buf);
simdjson_really_inline error_code visit_document_start(json_iterator &iter);
simdjson_really_inline error_code visit_object_start(json_iterator &iter);
simdjson_really_inline error_code visit_key(json_iterator &iter, const uint8_t *key);
simdjson_really_inline error_code visit_primitive(json_iterator &iter, const uint8_t *value);
simdjson_really_inline error_code visit_array_start(json_iterator &iter);
simdjson_really_inline error_code visit_array_end(json_iterator &iter);
simdjson_really_inline error_code visit_object_end(json_iterator &iter);
simdjson_really_inline error_code visit_document_end(json_iterator &iter);
simdjson_really_inline error_code visit_empty_array(json_iterator &iter);
simdjson_really_inline error_code visit_empty_object(json_iterator &iter);
simdjson_really_inline error_code visit_root_primitive(json_iterator &iter, const uint8_t *value);
simdjson_really_inline error_code increment_count(json_iterator &iter);
private:
// Since we only care about one thing at each level, we just use depth as the marker for what
// object/array we're nested inside.
enum class containers {
document = 0, //
top_object = 1, // {
statuses = 2, // { "statuses": [
tweet = 3, // { "statuses": [ {
user = 4 // { "statuses": [ { "user": {
};
/**
* The largest depth we care about.
* There can be things at lower depths.
*/
static constexpr uint32_t MAX_SUPPORTED_DEPTH = uint32_t(containers::user);
static constexpr const char *STATE_NAMES[] = {
"document",
"top object",
"statuses",
"tweet",
"user"
};
enum class field_type {
any,
unsigned_integer,
string,
nullable_unsigned_integer,
object,
array
};
struct field {
const char * key{};
size_t len{0};
size_t offset;
containers container{containers::document};
field_type type{field_type::any};
};
containers container{containers::document};
std::vector<tweet> &tweets;
uint8_t *current_string_buf_loc;
const uint8_t *current_key{};
simdjson_really_inline bool in_container(json_iterator &iter);
simdjson_really_inline bool in_container_child(json_iterator &iter);
simdjson_really_inline void start_container(json_iterator &iter);
simdjson_really_inline void end_container(json_iterator &iter);
simdjson_really_inline error_code parse_nullable_unsigned(json_iterator &iter, const uint8_t *value, const field &f);
simdjson_really_inline error_code parse_unsigned(json_iterator &iter, const uint8_t *value, const field &f);
simdjson_really_inline error_code parse_string(json_iterator &iter, const uint8_t *value, const field &f);
struct field_lookup {
field entries[256]{};
field_lookup();
simdjson_really_inline field get(const uint8_t * key, containers container);
private:
simdjson_really_inline uint8_t hash(const char * key, uint32_t depth);
simdjson_really_inline void add(const char * key, size_t len, containers container, field_type type, size_t offset);
simdjson_really_inline void neg(const char * const key, uint32_t depth);
};
static field_lookup fields;
}; // sax_tweet_reader_visitor
sax_tweet_reader_visitor::sax_tweet_reader_visitor(std::vector<tweet> &_tweets, uint8_t *string_buf)
: tweets{_tweets},
current_string_buf_loc{string_buf} {
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_document_start(json_iterator &iter) {
start_container(iter);
return SUCCESS;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_array_start(json_iterator &iter) {
// If we're not in a container we care about, don't bother with the rest
if (!in_container_child(iter)) { return SUCCESS; }
// Handle fields first
if (current_key) {
switch (fields.get(current_key, container).type) {
case field_type::array: // { "statuses": [
start_container(iter);
return SUCCESS;
case field_type::any:
return SUCCESS;
case field_type::object:
case field_type::unsigned_integer:
case field_type::nullable_unsigned_integer:
case field_type::string:
iter.log_error("unexpected array field");
return INCORRECT_TYPE;
}
}
// We're not in a field, so it must be a child of an array. We support any of those.
iter.log_error("unexpected array");
return INCORRECT_TYPE;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_object_start(json_iterator &iter) {
// If we're not in a container we care about, don't bother with the rest
if (!in_container_child(iter)) { return SUCCESS; }
// Handle known fields
if (current_key) {
auto f = fields.get(current_key, container);
switch (f.type) {
case field_type::object: // { "statuses": [ { "user": {
start_container(iter);
return SUCCESS;
case field_type::any:
return SUCCESS;
case field_type::array:
case field_type::unsigned_integer:
case field_type::nullable_unsigned_integer:
case field_type::string:
iter.log_error("unexpected object field");
return INCORRECT_TYPE;
}
}
// It's not a field, so it's a child of an array or document
switch (container) {
case containers::document: // top_object: {
case containers::statuses: // tweet: { "statuses": [ {
start_container(iter);
return SUCCESS;
case containers::top_object:
case containers::tweet:
case containers::user:
iter.log_error("unexpected object");
return INCORRECT_TYPE;
}
SIMDJSON_UNREACHABLE();
return UNINITIALIZED;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_key(json_iterator &, const uint8_t *key) {
current_key = key;
return SUCCESS;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_primitive(json_iterator &iter, const uint8_t *value) {
// Don't bother unless we're in a container we care about
if (!in_container(iter)) { return SUCCESS; }
// Handle fields first
if (current_key) {
auto f = fields.get(current_key, container);
switch (f.type) {
case field_type::unsigned_integer:
return parse_unsigned(iter, value, f);
case field_type::nullable_unsigned_integer:
return parse_nullable_unsigned(iter, value, f);
case field_type::string:
return parse_string(iter, value, f);
case field_type::any:
return SUCCESS;
case field_type::array:
case field_type::object:
iter.log_error("unexpected primitive");
return INCORRECT_TYPE;
}
}
// If it's not a field, it's a child of an array.
// The only array we support is statuses, which must contain objects.
iter.log_error("unexpected primitive");
return INCORRECT_TYPE;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_array_end(json_iterator &iter) {
if (in_container(iter)) { end_container(iter); }
return SUCCESS;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_object_end(json_iterator &iter) {
if (in_container(iter)) { end_container(iter); }
return SUCCESS;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_document_end(json_iterator &iter) {
iter.log_end_value("document");
return SUCCESS;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_empty_array(json_iterator &) {
return SUCCESS;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_empty_object(json_iterator &) {
return SUCCESS;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::visit_root_primitive(json_iterator &iter, const uint8_t *) {
iter.log_error("unexpected root primitive");
return INCORRECT_TYPE;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::increment_count(json_iterator &) { return SUCCESS; }
simdjson_really_inline bool sax_tweet_reader_visitor::in_container(json_iterator &iter) {
return iter.depth == uint32_t(container);
}
simdjson_really_inline bool sax_tweet_reader_visitor::in_container_child(json_iterator &iter) {
return iter.depth == uint32_t(container) + 1;
}
simdjson_really_inline void sax_tweet_reader_visitor::start_container(json_iterator &iter) {
SIMDJSON_ASSUME(iter.depth <= MAX_SUPPORTED_DEPTH); // Asserts in debug mode
container = containers(iter.depth);
if (logger::LOG_ENABLED) { iter.log_start_value(STATE_NAMES[iter.depth]); }
}
simdjson_really_inline void sax_tweet_reader_visitor::end_container(json_iterator &iter) {
if (logger::LOG_ENABLED) { iter.log_end_value(STATE_NAMES[int(container)]); }
container = containers(int(container) - 1);
}
simdjson_really_inline error_code sax_tweet_reader_visitor::parse_nullable_unsigned(json_iterator &iter, const uint8_t *value, const field &f) {
iter.log_value(f.key);
auto i = reinterpret_cast<uint64_t *>(reinterpret_cast<char *>(&tweets.back() + f.offset));
if (auto error = numberparsing::parse_unsigned(value).get(*i)) {
// If number parsing failed, check if it's null before returning the error
if (!atomparsing::is_valid_null_atom(value)) { iter.log_error("expected number or null"); return error; }
i = 0;
}
return SUCCESS;
}
simdjson_really_inline error_code sax_tweet_reader_visitor::parse_unsigned(json_iterator &iter, const uint8_t *value, const field &f) {
iter.log_value(f.key);
auto i = reinterpret_cast<uint64_t *>(reinterpret_cast<char *>(&tweets.back() + f.offset));
return numberparsing::parse_unsigned(value).get(*i);
}
simdjson_really_inline error_code sax_tweet_reader_visitor::parse_string(json_iterator &iter, const uint8_t *value, const field &f) {
iter.log_value(f.key);
auto s = reinterpret_cast<std::string_view *>(reinterpret_cast<char *>(&tweets.back() + f.offset));
return stringparsing::parse_string_to_buffer(value, current_string_buf_loc, *s);
}
sax_tweet_reader_visitor::field_lookup sax_tweet_reader_visitor::fields{};
simdjson_really_inline uint8_t sax_tweet_reader_visitor::field_lookup::hash(const char * key, uint32_t depth) {
// These shift numbers were chosen specifically because this yields only 2 collisions between
// keys in twitter.json, leaves 0 as a distinct value, and has 0 collisions between keys we
// actually care about.
return uint8_t((key[0] << 0) ^ (key[1] << 3) ^ (key[2] << 3) ^ (key[3] << 1) ^ depth);
}
simdjson_really_inline sax_tweet_reader_visitor::field sax_tweet_reader_visitor::field_lookup::get(const uint8_t * key, containers c) {
auto index = hash((const char *)key, uint32_t(c));
auto entry = entries[index];
// TODO if any key is > SIMDJSON_PADDING, this will access inaccessible memory!
if (c != entry.container || memcmp(key, entry.key, entry.len)) { return entries[0]; }
return entry;
}
simdjson_really_inline void sax_tweet_reader_visitor::field_lookup::add(const char * key, size_t len, containers c, field_type type, size_t offset) {
auto index = hash(key, uint32_t(c));
if (index == 0) {
fprintf(stderr, "%s (depth %d) hashes to zero, which is used as 'missing value'\n", key, int(c));
assert(false);
}
if (entries[index].key) {
fprintf(stderr, "%s (depth %d) collides with %s (depth %d) !\n", key, int(c), entries[index].key, int(entries[index].container));
assert(false);
}
entries[index] = { key, len, offset, c, type };
}
simdjson_really_inline void sax_tweet_reader_visitor::field_lookup::neg(const char * const key, uint32_t depth) {
auto index = hash(key, depth);
if (entries[index].key) {
fprintf(stderr, "%s (depth %d) conflicts with %s (depth %d) !\n", key, depth, entries[index].key, int(entries[index].container));
assert(false);
}
}
sax_tweet_reader_visitor::field_lookup::field_lookup() {
add("\"statuses\"", strlen("\"statuses\""), containers::top_object, field_type::array, 0); // { "statuses": [...]
#define TWEET_FIELD(KEY, TYPE) add("\"" #KEY "\"", strlen("\"" #KEY "\""), containers::tweet, TYPE, offsetof(tweet, KEY));
TWEET_FIELD(id, field_type::unsigned_integer);
TWEET_FIELD(in_reply_to_status_id, field_type::nullable_unsigned_integer);
TWEET_FIELD(retweet_count, field_type::unsigned_integer);
TWEET_FIELD(favorite_count, field_type::unsigned_integer);
TWEET_FIELD(text, field_type::string);
TWEET_FIELD(created_at, field_type::string);
TWEET_FIELD(user, field_type::object)
#undef TWEET_FIELD
#define USER_FIELD(KEY, TYPE) add("\"" #KEY "\"", strlen("\"" #KEY "\""), containers::user, TYPE, offsetof(tweet, user)+offsetof(twitter_user, KEY));
USER_FIELD(id, field_type::unsigned_integer);
USER_FIELD(screen_name, field_type::string);
#undef USER_FIELD
// Check for collisions with other (unused) hash keys in typical twitter JSON
#define NEG(key, depth) neg("\"" #key "\"", depth);
NEG(display_url, 9);
NEG(expanded_url, 9);
neg("\"h\":", 9);
NEG(indices, 9);
NEG(resize, 9);
NEG(url, 9);
neg("\"w\":", 9);
NEG(display_url, 8);
NEG(expanded_url, 8);
neg("\"h\":", 8);
NEG(indices, 8);
NEG(large, 8);
NEG(medium, 8);
NEG(resize, 8);
NEG(small, 8);
NEG(thumb, 8);
NEG(url, 8);
neg("\"w\":", 8);
NEG(display_url, 7);
NEG(expanded_url, 7);
NEG(id_str, 7);
NEG(id, 7);
NEG(indices, 7);
NEG(large, 7);
NEG(media_url_https, 7);
NEG(media_url, 7);
NEG(medium, 7);
NEG(name, 7);
NEG(sizes, 7);
NEG(small, 7);
NEG(source_status_id_str, 7);
NEG(source_status_id, 7);
NEG(thumb, 7);
NEG(type, 7);
NEG(url, 7);
NEG(urls, 7);
NEG(description, 6);
NEG(display_url, 6);
NEG(expanded_url, 6);
NEG(id_str, 6);
NEG(id, 6);
NEG(indices, 6);
NEG(media_url_https, 6);
NEG(media_url, 6);
NEG(name, 6);
NEG(sizes, 6);
NEG(source_status_id_str, 6);
NEG(source_status_id, 6);
NEG(type, 6);
NEG(url, 6);
NEG(urls, 6);
NEG(contributors_enabled, 5);
NEG(default_profile_image, 5);
NEG(default_profile, 5);
NEG(description, 5);
NEG(entities, 5);
NEG(favourites_count, 5);
NEG(follow_request_sent, 5);
NEG(followers_count, 5);
NEG(following, 5);
NEG(friends_count, 5);
NEG(geo_enabled, 5);
NEG(hashtags, 5);
NEG(id_str, 5);
NEG(id, 5);
NEG(is_translation_enabled, 5);
NEG(is_translator, 5);
NEG(iso_language_code, 5);
NEG(lang, 5);
NEG(listed_count, 5);
NEG(location, 5);
NEG(media, 5);
NEG(name, 5);
NEG(notifications, 5);
NEG(profile_background_color, 5);
NEG(profile_background_image_url_https, 5);
NEG(profile_background_image_url, 5);
NEG(profile_background_tile, 5);
NEG(profile_banner_url, 5);
NEG(profile_image_url_https, 5);
NEG(profile_image_url, 5);
NEG(profile_link_color, 5);
NEG(profile_sidebar_border_color, 5);
NEG(profile_sidebar_fill_color, 5);
NEG(profile_text_color, 5);
NEG(profile_use_background_image, 5);
NEG(protected, 5);
NEG(result_type, 5);
NEG(statuses_count, 5);
NEG(symbols, 5);
NEG(time_zone, 5);
NEG(url, 5);
NEG(urls, 5);
NEG(user_mentions, 5);
NEG(utc_offset, 5);
NEG(verified, 5);
NEG(contributors_enabled, 4);
NEG(contributors, 4);
NEG(coordinates, 4);
NEG(default_profile_image, 4);
NEG(default_profile, 4);
NEG(description, 4);
NEG(entities, 4);
NEG(favorited, 4);
NEG(favourites_count, 4);
NEG(follow_request_sent, 4);
NEG(followers_count, 4);
NEG(following, 4);
NEG(friends_count, 4);
NEG(geo_enabled, 4);
NEG(geo, 4);
NEG(hashtags, 4);
NEG(id_str, 4);
NEG(in_reply_to_screen_name, 4);
NEG(in_reply_to_status_id_str, 4);
NEG(in_reply_to_user_id_str, 4);
NEG(in_reply_to_user_id, 4);
NEG(is_translation_enabled, 4);
NEG(is_translator, 4);
NEG(iso_language_code, 4);
NEG(lang, 4);
NEG(listed_count, 4);
NEG(location, 4);
NEG(media, 4);
NEG(metadata, 4);
NEG(name, 4);
NEG(notifications, 4);
NEG(place, 4);
NEG(possibly_sensitive, 4);
NEG(profile_background_color, 4);
NEG(profile_background_image_url_https, 4);
NEG(profile_background_image_url, 4);
NEG(profile_background_tile, 4);
NEG(profile_banner_url, 4);
NEG(profile_image_url_https, 4);
NEG(profile_image_url, 4);
NEG(profile_link_color, 4);
NEG(profile_sidebar_border_color, 4);
NEG(profile_sidebar_fill_color, 4);
NEG(profile_text_color, 4);
NEG(profile_use_background_image, 4);
NEG(protected, 4);
NEG(result_type, 4);
NEG(retweeted, 4);
NEG(source, 4);
NEG(statuses_count, 4);
NEG(symbols, 4);
NEG(time_zone, 4);
NEG(truncated, 4);
NEG(url, 4);
NEG(urls, 4);
NEG(user_mentions, 4);
NEG(utc_offset, 4);
NEG(verified, 4);
NEG(contributors, 3);
NEG(coordinates, 3);
NEG(entities, 3);
NEG(favorited, 3);
NEG(geo, 3);
NEG(id_str, 3);
NEG(in_reply_to_screen_name, 3);
NEG(in_reply_to_status_id_str, 3);
NEG(in_reply_to_user_id_str, 3);
NEG(in_reply_to_user_id, 3);
NEG(lang, 3);
NEG(metadata, 3);
NEG(place, 3);
NEG(possibly_sensitive, 3);
NEG(retweeted_status, 3);
NEG(retweeted, 3);
NEG(source, 3);
NEG(truncated, 3);
NEG(completed_in, 2);
NEG(count, 2);
NEG(max_id_str, 2);
NEG(max_id, 2);
NEG(next_results, 2);
NEG(query, 2);
NEG(refresh_url, 2);
NEG(since_id_str, 2);
NEG(since_id, 2);
NEG(search_metadata, 1);
#undef NEG
}
// sax_tweet_reader_visitor::field_lookup::find_min() {
// int min_count = 100000;
// for (int a=0;a<4;a++) {
// for (int b=0;b<4;b++) {
// for (int c=0;c<4;c++) {
// twitter::sax_tweet_reader_visitor::field_lookup fields(a,b,c);
// if (fields.collision_count) { continue; }
// if (fields.zero_emission) { continue; }
// if (fields.conflict_count < min_count) { printf("min=%d,%d,%d (%d)", a, b, c, fields.conflict_count); }
// }
// }
// }
// }
} // namespace twitter
SIMDJSON_UNTARGET_REGION
#endif // TWITTER_SAX_TWEET_READER_VISITOR_H
+21
View File
@@ -0,0 +1,21 @@
#ifndef TWEET_H
#define TWEET_H
#include "simdjson.h"
#include "twitter_user.h"
namespace twitter {
struct tweet {
uint64_t id{};
std::string_view text{};
std::string_view created_at{};
uint64_t in_reply_to_status_id{};
uint64_t retweet_count{};
uint64_t favorite_count{};
twitter_user user{};
};
} // namespace twitter
#endif // TWEET_H
+15
View File
@@ -0,0 +1,15 @@
#ifndef TWITTER_USER_H
#define TWITTER_USER_H
#include "simdjson.h"
namespace twitter {
struct twitter_user {
uint64_t id{};
std::string_view screen_name{};
};
} // namespace twitter
#endif // TWITTER_USER_H
+49
View File
@@ -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()
+152
View File
@@ -0,0 +1,152 @@
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()
option(SIMDJSON_VISUAL_STUDIO_BUILD_WITH_DEBUG_INFO_FOR_PROFILING "Under Visual Studio, add Zi to the compile flag and DEBUG to the link file to add debugging information to the release build for easier profiling inside tools like VTune" OFF)
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 /w34714) # https://docs.microsoft.com/en-us/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4714?view=vs-2019
endif()
if(SIMDJSON_VISUAL_STUDIO_BUILD_WITH_DEBUG_INFO_FOR_PROFILING)
target_link_options(simdjson-flags INTERFACE /DEBUG )
target_compile_options(simdjson-flags INTERFACE /Zi)
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_BASH "Allow usage of bash within CMake" ON)
option(SIMDJSON_GIT "Allow usage of git within CMake" ON)
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()
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)
+24
View File
@@ -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})
+89
View File
@@ -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_GIT 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()
Vendored Submodule
+1
Submodule dependencies/cxxopts added at 794c975287
+463 -68
View File
@@ -3,20 +3,35 @@ 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](#c11-support-and-string_view)
* [C++17 Support](#c17-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)
* [Standard Compliance](#standard-compliance)
Requirements
------------------
- A recent compiler (LLVM clang6 or better, GNU GCC 7.4 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 +42,56 @@ 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++ -std=c++17 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 with package managers
------------------
You can install the simdjson library on your system or in your project using multiple package managers such as MSYS2, the conan package manager, vcpkg, brew, the apt package manager (debian-based Linux systems), the FreeBSD package manager (FreeBSD), and so on. [Visit our wiki for more details](https://github.com/simdjson/simdjson/wiki/Installing-simdjson-with-a-package-manager).
Using simdjson as a CMake dependency
------------------
You can include the simdjson as a CMake dependency by including the following lines in your `CMakeLists.txt`:
```cmake
include(FetchContent)
FetchContent_Declare(
simdjson
GIT_REPOSITORY https://github.com/simdjson/simdjson.git
GIT_TAG v0.5.0
GIT_SHALLOW TRUE)
set(SIMDJSON_JUST_LIBRARY ON CACHE INTERNAL "")
set(SIMDJSON_BUILD_STATIC ON CACHE INTERNAL "")
FetchContent_MakeAvailable(simdjson)
```
You should replace `GIT_TAG v0.5.0` by the version you need. If you omit `GIT_TAG v0.5.0`, you will work from the main branch of simdjson: we recommend that if you are working on production code,
Elsewhere in your project, you can declare dependencies on simdjson with lines such as these:
```cmake
add_executable(myprogram myprogram.cpp)
target_link_libraries(myprogram simdjson)
```
We recommend CMake version 3.15 or better.
See [our CMake demonstration](https://github.com/simdjson/cmake_demo_single_file). It works under Linux, FreeBSD, macOS and Windows (including Visual Studio).
The CMake build in simdjson can be taylored with a few variables. You can see the available variables and their default values by entering the `cmake -LA` command.
The Basics: Loading and Parsing JSON Documents
----------------------------------------------
@@ -49,16 +111,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 +144,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 +161,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,17 +179,136 @@ 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
------------
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:
`at_pointer()` method, letting you reach further down into the document in a single call:
```c++
auto cars_json = R"( [
@@ -116,35 +318,75 @@ auto cars_json = R"( [
] )"_padded;
dom::parser parser;
dom::element cars = parser.parse(cars_json);
cout << cars.at("0/tire_pressure/1") << endl; // Prints 39.9
cout << cars.at_pointer("/0/tire_pressure/1") << endl; // Prints 39.9
```
A JSON Path is a sequence of segments each starting with the '/' character. Within arrays, an integer
index allows you to select the indexed node. Within objects, the string value of the key allows you to
select the value. If your keys contain the characters '/' or '~', they must be escaped as '~1' and
'~0' respectively. An empty JSON Path refers to the whole document.
We also extend the JSON Pointer support to include *relative* paths.
You can apply a JSON path to any node and the path gets interpreted relatively, as if the currrent node were a whole JSON document.
Consider the following example:
```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 ] }
] )"_padded;
dom::parser parser;
dom::element cars = parser.parse(cars_json);
cout << cars.at_pointer("/0/tire_pressure/1") << endl; // Prints 39.9
for (dom::element car_element : cars) {
dom::object car;
simdjson::error_code error;
if ((error = car_element.get(car))) { std::cerr << error << std::endl; return; }
double x = car.at_pointer("/tire_pressure/1");
cout << x << endl; // Prints 39.9, 31 and 30
}
```
Error Handling
--------------
All simdjson APIs that can fail return `simdjson_result<T>`, which is a &lt;value, error_code&gt;
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 +394,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 +519,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 +580,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 +592,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 +601,47 @@ 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
Standard Compliance
--------------------
The simdjson library is fully compliant with the [RFC 8259](https://www.tbray.org/ongoing/When/201x/2017/12/14/rfc8259.html) JSON specification.
- The only insignificant whitespace characters allowed are the space, the horizontal tab, the line feed and the carriage return. In particular, a JSON document may not contain an unespaced null character.
- A single string or a single number is considered to be a valid JSON document.
- We fully validate the numbers according to the JSON specification. For example, the string `01` is not valid JSON document since the specification states that *leading zeros are not allowed*.
- The specification allows implementations to set limits on the range and precision of numbers accepted. We support 64-bit floating-point numbers as well as integer values.
- We parse integers and floating-point numbers as separate types which allows us to support all signed (two complement's) 64-bit integers, like a Java `long` or a C/C++ `long long` and all 64-bit unsigned integers. When we cannot represent exactly an integer as a signed or unsigned 64-bit value, we reject the JSON document.
- We support the full range of 64-bit floating-point numbers (binary64). The values range from `std::numeric_limits<double>::lowest()` to `std::numeric_limits<double>::max()`, so from -1.7976e308 all the way to 1.7975e308. Extreme values (less or equal to -1e308, greater or equal to 1e308) are rejected: we refuse to parse the input document. Numbers are parsed with with a perfect accuracy (ULP 0): the nearest floating-point value is chosen, rounding to even when needed. If you serialized your floating-point numbers with 17 significant digits in a standard compliant manner, the simdjson library is guaranteed to recovere the example same numbers, exactly.
- The specification states that JSON text exchanged between systems that are not part of a closed ecosystem MUST be encoded using UTF-8. The simdjson library does full UTF-8 validation as part of the parsing. The specification states that implementations MUST NOT add a byte order mark: the simdjson library rejects documents starting with a byte order mark.
- The simdjson library validates string content for unescaped characters. Unescaped line breaks and tabs in strings are not allowed.
- The simdjson library accepts objects with repeated keys: all of the name/value pairs, including duplicates, are reported. We do not enforce key uniqueness.
- The specification states that an implementation may set limits on the size of texts that it accepts. The simdjson library limits single JSON documents to 4 GiB. It will refuse to parse a JSON document larger than 4294967295 bytes. (This limitation does not apply to streams of JSON documents, only to single JSON documents.)
- The specification states that an implementation may set limits on the maximum depth of nesting. By default, the simdjson will refuse to parse documents with a depth exceeding 1024.
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.
+607
View File
@@ -0,0 +1,607 @@
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++ -std=c++17 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 with package managers
------------------
You can install the simdjson library on your system or in your project using multiple package managers such as MSYS2, the conan package manager, vcpkg, brew, the apt package manager (debian-based Linux systems), the FreeBSD package manager (FreeBSD), and so on. [Visit our wiki for more details](https://github.com/simdjson/simdjson/wiki/Installing-simdjson-with-a-package-manager).
Using simdjson as a CMake dependency
------------------
You can include the simdjson as a CMake dependency by including the following lines in your `CMakeLists.txt`:
```
include(FetchContent)
FetchContent_Declare(
simdjson
GIT_REPOSITORY https://github.com/simdjson/simdjson.git
GIT_TAG v0.4.7
GIT_SHALLOW TRUE)
set(SIMDJSON_JUST_LIBRARY ON CACHE INTERNAL "")
set(SIMDJSON_BUILD_STATIC ON CACHE INTERNAL "")
FetchContent_MakeAvailable(simdjson)
```
You should replace `GIT_TAG v0.5.0` by the version you need. If you omit `GIT_TAG v0.5.0`, you will work from the main branch of simdjson: we recommend that if you are working on production code,
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)
```
We recommend CMake version 3.15 or better.
See [our CMake demonstration](https://github.com/simdjson/cmake_demo_single_file). It works under Linux, FreeBSD, macOS and Windows (including Visual Studio).
The CMake build in simdjson can be taylored with a few variables. You can see the available variables and their default values by entering the `cmake -LA` command.
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_pointer()` method, letting you reach further down into the document in a single call:
```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 ] }
] )"_padded;
dom::parser parser;
dom::element cars = parser.parse(cars_json);
cout << cars.at_pointer("/0/tire_pressure/1") << endl; // Prints 39.9
```
A JSON Path is a sequence of segments each starting with the '/' character. Within arrays, an integer
index allows you to select the indexed node. Within objects, the string value of the key allows you to
select the value. If your keys contain the characters '/' or '~', they must be escaped as '~1' and
'~0' respectively. An empty JSON Path refers to the whole document.
We also extend the JSON Pointer support to include *relative* paths.
You can apply a JSON path to any node and the path gets interpreted relatively, as if the currrent node were a whole JSON document.
Consider the following example:
```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 ] }
] )"_padded;
dom::parser parser;
dom::element cars = parser.parse(cars_json);
cout << cars.at_pointer("/0/tire_pressure/1") << endl; // Prints 39.9
for (dom::element car_element : cars) {
dom::object car;
simdjson::error_code error;
if ((error = car_element.get(car))) { std::cerr << error << std::endl; return; }
double x = car.at_pointer("/tire_pressure/1");
cout << x << endl; // Prints 39.9, 31 and 30
}
```
Error Handling
--------------
All simdjson APIs that can fail return `simdjson_result<T>`, which is a &lt;value, error_code&gt;
pair. You can retrieve the value with .get(), 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.
+1 -1
View File
@@ -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
View File
@@ -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.
+54 -20
View File
@@ -8,14 +8,18 @@ are still some scenarios where tuning can enhance performance.
* [Keeping documents around for longer](#keeping-documents-around-for-longer)
* [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)
* [Best Use of the DOM API](#best-use-of-the-dom-api)
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 +39,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 +65,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 +82,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; }
// ...
@@ -115,18 +121,6 @@ use the `-H` flag to omit the memory allocation cost from the benchmark results.
./parse -H largefile # without memory allocation
```
Computed GOTOs
--------------
For best performance, we use a technique called "computed goto" when the compiler supports it, it is
also sometimes described as "Labels as Values". Though it is not part of the C++ standard, it is
supported by many major compilers and it brings measurable performance benefits that are difficult
to achieve otherwise. The computed gotos are automatically disabled under Visual Studio.
If you wish to forcefully disable computed gotos, you can do so by compiling the code with
`-DSIMDJSON_NO_COMPUTED_GOTO=1`. It is not recommended to disable computed gotos if your compiler
supports it. In fact, you should almost never need to be concerned with computed gotos.
Number parsing
--------------
@@ -140,3 +134,43 @@ 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.
When compiling with Visual Studio, we recommend the flags `/Ob2 /O2` or better. 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 (ClangCL). 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. Meanwhile the [LLVM CLang compiler is binary compatible with Visual Studio](https://clang.llvm.org/docs/MSVCCompatibility.html) which means that you can combine their binaries (executables and libraries).
Under Windows, we also support the GNU GCC compiler via MSYS2. The performance of 64-bit MSYS2 under Windows excellent (on par with Linux).
Downclocking
--------------
SIMD instructions are the public transportation of computing. Instead of using 4 distinct instructions to add numbers, you can replace them with a single instruction that does the same work. Though the one instruction is slightly more expensive, the energy used per unit of work is much less with SIMD. If you can increase your speed using SIMD instructions (NEON, SSE, AVX), you should expect to reduce your power usage.
The SIMD instructions that simdjson relies upon (SSE and AVX under x64, NEON under ARM) are routinely part of runtime libraries (e.g., [Go](https://golang.org/src/runtime/memmove_amd64.s), [Glibc](https://github.com/ihtsae/glibc/commit/5f3d0b78e011d2a72f9e88b0e9ef5bc081d18f97), [LLVM](https://github.com/llvm/llvm-project/blob/96f3ea0d21b48ca088355db10d4d1a2e9bc9f884/lldb/tools/debugserver/source/MacOSX/i386/DNBArchImplI386.cpp), [Rust](https://github.com/rust-lang/rust/commit/070fad1701fb36b112853b0a6a9787a7bb7ff34c), [Java](http://hg.openjdk.java.net/jdk8u/jdk8u/hotspot/file/c1374141598c/src/cpu/x86/vm/stubGenerator_x86_64.cpp#l1297), [PHP](https://github.com/php/php-src/blob/e5cb53ec68603d4dbdd780fd3ecfca943b4fd383/ext/standard/string.c)). What distinguishes the simdjson library is that it is built from the ground up to benefit from these instructions.
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. We do use vectorized multiplications, but only using 128-bit registers. 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) by simdjson. Thus even if your CPU supports AVX2, you do not need to use AVX2. You are in control.
Best Use of the DOM API
-------------------------
The simdjson API provides access to the JSON DOM (document-object-model) content as a tree of `dom::element` instances, each representing an object, an array or an atomic type (null, true, false, number). These `dom::element` instances are lightweight objects (e.g., spanning 16 bytes) and it might be advantageous to pass them by value, as opposed to passing them by reference or by pointer.
-1
View File
@@ -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.
+1
View File
@@ -0,0 +1 @@
add_subdirectory(quickstart)
+60
View File
@@ -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()
+20 -4
View File
@@ -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
+2 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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:
+28 -16
View File
@@ -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
View File
@@ -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;
}
+6 -6
View File
@@ -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;
SIMDJSON_UNUSED auto dumpstatus = elem.dump_raw_tape(os);
return 0;
}
+10 -5
View File
@@ -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 -3
View File
@@ -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;
SIMDJSON_UNUSED simdjson::dom::element elem;
SIMDJSON_UNUSED auto error = parser.parse(Data, Size).get(elem);
return 0;
}
+5 -6
View File
@@ -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;
}
+1 -1
View File
@@ -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
View File
@@ -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
View File
@@ -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)
+52 -10
View File
@@ -5,28 +5,70 @@
* @mainpage
*
* Check the [README.md](https://github.com/lemire/simdjson/blob/master/README.md#simdjson--parsing-gigabytes-of-json-per-second).
*
* Sample code. See https://github.com/simdjson/simdjson/blob/master/doc/basics.md for more examples.
#include "simdjson.h"
int main(void) {
// load from `twitter.json` file:
simdjson::dom::parser parser;
simdjson::dom::element tweets = parser.load("twitter.json");
std::cout << tweets["search_metadata"]["count"] << " results." << std::endl;
// Parse and iterate through an array of objects
auto abstract_json = R"( [
{ "12345" : {"a":12.34, "b":56.78, "c": 9998877} },
{ "12545" : {"a":11.44, "b":12.78, "c": 11111111} }
] )"_padded;
for (simdjson::dom::object obj : parser.parse(abstract_json)) {
for(const auto& key_value : obj) {
cout << "key: " << key_value.key << " : ";
simdjson::dom::object innerobj = key_value.value;
cout << "a: " << double(innerobj["a"]) << ", ";
cout << "b: " << double(innerobj["b"]) << ", ";
cout << "c: " << int64_t(innerobj["c"]) << endl;
}
}
}
*/
#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/document_stream.h"
#include "simdjson/inline/error.h"
#include "simdjson/inline/padded_string.h"
#include "simdjson/inline/parsedjson_iterator.h"
#include "simdjson/dom/array-inl.h"
#include "simdjson/dom/document_stream-inl.h"
#include "simdjson/dom/document-inl.h"
#include "simdjson/dom/element-inl.h"
#include "simdjson/error-inl.h"
#include "simdjson/dom/object-inl.h"
#include "simdjson/padded_string-inl.h"
#include "simdjson/dom/parsedjson_iterator-inl.h"
#include "simdjson/dom/parser-inl.h"
#include "simdjson/internal/tape_ref-inl.h"
SIMDJSON_POP_DISABLE_WARNINGS
#endif // SIMDJSON_H
+144 -58
View File
@@ -37,77 +37,163 @@ 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 SIMDJSON_BEGIN_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-BEGIN " #name);
#define SIMDJSON_END_DEBUG_BLOCK(name) __asm volatile("# LLVM-MCA-END " #name);
#define SIMDJSON_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)
#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
#define SIMDJSON_BEGIN_DEBUG_BLOCK(name)
#define SIMDJSON_END_DEBUG_BLOCK(name)
#define SIMDJSON_DEBUG_BLOCK(name, block)
#endif
// Align to N-byte boundary
#define ROUNDUP_N(a, n) (((a) + ((n)-1)) & ~((n)-1))
#define ROUNDDOWN_N(a, n) ((a) & ~((n)-1))
#define SIMDJSON_ROUNDUP_N(a, n) (((a) + ((n)-1)) & ~((n)-1))
#define SIMDJSON_ROUNDDOWN_N(a, n) ((a) & ~((n)-1))
#define ISALIGNED_N(ptr, n) (((uintptr_t)(ptr) & ((n)-1)) == 0)
#define SIMDJSON_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 simdjson_really_inline __forceinline
#define simdjson_never_inline __declspec(noinline)
#ifndef likely
#define likely(x) x
#endif
#ifndef unlikely
#define unlikely(x) x
#endif
#define SIMDJSON_UNUSED
#define SIMDJSON_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 simdjson_likely
#define simdjson_likely(x) x
#endif
#ifndef simdjson_unlikely
#define simdjson_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 simdjson_really_inline inline __attribute__((always_inline))
#define simdjson_never_inline inline __attribute__((noinline))
#define SIMDJSON_UNUSED __attribute__((unused))
#define SIMDJSON_WARN_UNUSED __attribute__((warn_unused_result))
#ifndef simdjson_likely
#define simdjson_likely(x) __builtin_expect(!!(x), 1)
#endif
#ifndef simdjson_unlikely
#define simdjson_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
+17 -2
View File
@@ -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
-143
View File
@@ -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
+195
View File
@@ -0,0 +1,195 @@
#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
//
simdjson_really_inline simdjson_result<dom::array>::simdjson_result() noexcept
: internal::simdjson_result_base<dom::array>() {}
simdjson_really_inline simdjson_result<dom::array>::simdjson_result(dom::array value) noexcept
: internal::simdjson_result_base<dom::array>(std::forward<dom::array>(value)) {}
simdjson_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_pointer(std::string_view json_pointer) const noexcept {
if (error()) { return error(); }
return first.at_pointer(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
//
simdjson_really_inline array::array() noexcept : tape{} {}
simdjson_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_pointer(std::string_view json_pointer) const noexcept {
if(json_pointer[0] != '/') {
if(json_pointer.size() == 0) { // an empty string means that we return the current node
return element(this->tape); // copy the current node
} else { // otherwise there is an error
return INVALID_JSON_POINTER;
}
}
json_pointer = json_pointer.substr(1);
// - 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 an error, it ends here
if(child.error()) {
return child;
}
// If there is a /, we're not done yet, call recursively.
if (i < json_pointer.length()) {
child = child.at_pointer(json_pointer.substr(i));
}
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
//
simdjson_really_inline array::iterator::iterator(const internal::tape_ref &_tape) noexcept : tape{_tape} { }
inline element array::iterator::operator*() const noexcept {
return element(tape);
}
inline array::iterator& array::iterator::operator++() noexcept {
tape.json_index = tape.after_element();
return *this;
}
inline array::iterator array::iterator::operator++(int) noexcept {
array::iterator out = *this;
++*this;
return out;
}
inline bool array::iterator::operator!=(const array::iterator& other) const noexcept {
return tape.json_index != other.tape.json_index;
}
inline bool array::iterator::operator==(const array::iterator& other) const noexcept {
return tape.json_index == other.tape.json_index;
}
inline bool array::iterator::operator<(const array::iterator& other) const noexcept {
return tape.json_index < other.tape.json_index;
}
inline bool array::iterator::operator<=(const array::iterator& other) const noexcept {
return tape.json_index <= other.tape.json_index;
}
inline bool array::iterator::operator>=(const array::iterator& other) const noexcept {
return tape.json_index >= other.tape.json_index;
}
inline bool array::iterator::operator>(const array::iterator& other) const noexcept {
return tape.json_index > other.tape.json_index;
}
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
#include "simdjson/dom/element-inl.h"
#if defined(__cpp_lib_ranges)
static_assert(std::ranges::view<simdjson::dom::array>);
static_assert(std::ranges::sized_range<simdjson::dom::array>);
#if SIMDJSON_EXCEPTIONS
static_assert(std::ranges::view<simdjson::simdjson_result<simdjson::dom::array>>);
static_assert(std::ranges::sized_range<simdjson::simdjson_result<simdjson::dom::array>>);
#endif // SIMDJSON_EXCEPTIONS
#endif // defined(__cpp_lib_ranges)
#endif // SIMDJSON_INLINE_ARRAY_H
+194
View File
@@ -0,0 +1,194 @@
#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 */
simdjson_really_inline array() noexcept;
class iterator {
public:
using value_type = element;
using difference_type = std::ptrdiff_t;
/**
* Get the actual value
*/
inline value_type operator*() const noexcept;
/**
* Get the next value.
*
* Part of the std::iterator interface.
*
*/
inline iterator& operator++() noexcept;
/**
* Get the next value.
*
* Part of the std::iterator interface.
*/
inline iterator operator++(int) 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;
inline bool operator==(const iterator& other) const noexcept;
inline bool operator<(const iterator& other) const noexcept;
inline bool operator<=(const iterator& other) const noexcept;
inline bool operator>=(const iterator& other) const noexcept;
inline bool operator>(const iterator& other) const noexcept;
iterator() noexcept = default;
iterator(const iterator&) noexcept = default;
iterator& operator=(const iterator&) noexcept = default;
private:
simdjson_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. We use the RFC 6901
* https://tools.ietf.org/html/rfc6901 standard, interpreting the current node
* as the root of its own JSON document.
*
* dom::parser parser;
* array a = parser.parse(R"([ { "foo": { "a": [ 10, 20, 30 ] }} ])"_padded);
* a.at_pointer("/0/foo/a/1") == 20
* a.at_pointer("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_pointer(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:
simdjson_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:
simdjson_really_inline simdjson_result() noexcept; ///< @private
simdjson_really_inline simdjson_result(dom::array value) noexcept; ///< @private
simdjson_really_inline simdjson_result(error_code error) noexcept; ///< @private
inline simdjson_result<dom::element> at_pointer(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
#if defined(__cpp_lib_ranges)
#include <ranges>
namespace std {
namespace ranges {
template<>
inline constexpr bool enable_view<simdjson::dom::array> = true;
#if SIMDJSON_EXCEPTIONS
template<>
inline constexpr bool enable_view<simdjson::simdjson_result<simdjson::dom::array>> = true;
#endif // SIMDJSON_EXCEPTIONS
} // namespace ranges
} // namespace std
#endif // defined(__cpp_lib_ranges)
#endif // SIMDJSON_DOM_ARRAY_H
+141
View File
@@ -0,0 +1,141 @@
#ifndef SIMDJSON_INLINE_DOCUMENT_H
#define SIMDJSON_INLINE_DOCUMENT_H
// Inline implementations go in here.
#include "simdjson/dom/document.h"
#include "simdjson/dom/element.h"
#include "simdjson/internal/tape_ref.h"
#include "simdjson/internal/jsonformatutils.h"
#include <ostream>
#include <cstring>
namespace simdjson {
namespace dom {
//
// document inline implementation
//
inline element document::root() const noexcept {
return element(internal::tape_ref(this, 1));
}
SIMDJSON_WARN_UNUSED
inline error_code document::allocate(size_t capacity) noexcept {
if (capacity == 0) {
string_buf.reset();
tape.reset();
return SUCCESS;
}
// a pathological input like "[[[[..." would generate len tape elements, so
// need a capacity of at least len + 1, but it is also possible to do
// worse with "[7,7,7,7,6,7,7,7,6,7,7,6,[7,7,7,7,6,7,7,7,6,7,7,6,7,7,7,7,7,7,6"
//where len + 1 tape elements are
// generated, see issue https://github.com/lemire/simdjson/issues/345
size_t tape_capacity = SIMDJSON_ROUNDUP_N(capacity + 3, 64);
// a document with only zero-length strings... could have len/3 string
// and we would need len/3 * 5 bytes on the string buffer
size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * capacity / 3 + 32, 64);
string_buf.reset( new (std::nothrow) uint8_t[string_capacity]);
tape.reset(new (std::nothrow) uint64_t[tape_capacity]);
return string_buf && tape ? SUCCESS : MEMALLOC;
}
inline bool document::dump_raw_tape(std::ostream &os) const noexcept {
uint32_t string_length;
size_t tape_idx = 0;
uint64_t tape_val = tape[tape_idx];
uint8_t type = uint8_t(tape_val >> 56);
os << tape_idx << " : " << type;
tape_idx++;
size_t how_many = 0;
if (type == 'r') {
how_many = size_t(tape_val & internal::JSON_VALUE_MASK);
} else {
// Error: no starting root node?
return false;
}
os << "\t// pointing to " << how_many << " (right after last node)\n";
uint64_t payload;
for (; tape_idx < how_many; tape_idx++) {
os << tape_idx << " : ";
tape_val = tape[tape_idx];
payload = tape_val & internal::JSON_VALUE_MASK;
type = uint8_t(tape_val >> 56);
switch (type) {
case '"': // we have a string
os << "string \"";
memcpy(&string_length, string_buf.get() + payload, sizeof(uint32_t));
os << internal::escape_json_string(std::string_view(
(const char *)(string_buf.get() + payload + sizeof(uint32_t)),
string_length
));
os << '"';
os << '\n';
break;
case 'l': // we have a long int
if (tape_idx + 1 >= how_many) {
return false;
}
os << "integer " << static_cast<int64_t>(tape[++tape_idx]) << "\n";
break;
case 'u': // we have a long uint
if (tape_idx + 1 >= how_many) {
return false;
}
os << "unsigned integer " << tape[++tape_idx] << "\n";
break;
case 'd': // we have a double
os << "float ";
if (tape_idx + 1 >= how_many) {
return false;
}
double answer;
memcpy(&answer, &tape[++tape_idx], sizeof(answer));
os << answer << '\n';
break;
case 'n': // we have a null
os << "null\n";
break;
case 't': // we have a true
os << "true\n";
break;
case 'f': // we have a false
os << "false\n";
break;
case '{': // we have an object
os << "{\t// pointing to next tape location " << payload
<< " (first node after the scope) \n";
break;
case '}': // we end an object
os << "}\t// pointing to previous tape location " << payload
<< " (start of the scope) \n";
break;
case '[': // we start an array
os << "[\t// pointing to next tape location " << payload
<< " (first node after the scope) \n";
break;
case ']': // we end an array
os << "]\t// pointing to previous tape location " << payload
<< " (start of the scope) \n";
break;
case 'r': // we start and end with the root node
// should we be hitting the root node?
return false;
default:
return false;
}
}
tape_val = tape[tape_idx];
payload = tape_val & internal::JSON_VALUE_MASK;
type = uint8_t(tape_val >> 56);
os << tape_idx << " : " << type << "\t// pointing to " << payload
<< " (start root)\n";
return true;
}
} // namespace dom
} // namespace simdjson
#endif // SIMDJSON_INLINE_DOCUMENT_H
+78
View File
@@ -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
+273
View File
@@ -0,0 +1,273 @@
#ifndef SIMDJSON_INLINE_DOCUMENT_STREAM_H
#define SIMDJSON_INLINE_DOCUMENT_STREAM_H
#include "simdjson/dom/document_stream.h"
#include <algorithm>
#include <limits>
#include <stdexcept>
namespace simdjson {
namespace dom {
#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;});
}
inline stage1_worker::~stage1_worker() {
stop_thread();
}
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.
}
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"
}
}
);
}
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
simdjson_really_inline document_stream::document_stream(
dom::parser &_parser,
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
, use_thread(_parser.threaded) // we need to make a copy because _parser.threaded can change
#endif
{
#ifdef SIMDJSON_THREADS_ENABLED
if(worker.get() == nullptr) {
error = MEMALLOC;
}
#endif
}
simdjson_really_inline document_stream::document_stream() noexcept
: parser{nullptr},
buf{nullptr},
len{0},
batch_size{0},
error{UNINITIALIZED}
#ifdef SIMDJSON_THREADS_ENABLED
, use_thread(false)
#endif
{
}
simdjson_really_inline document_stream::~document_stream() noexcept {
}
simdjson_really_inline document_stream::iterator document_stream::begin() noexcept {
start();
// If there are no documents, we're finished.
return iterator(*this, error == EMPTY);
}
simdjson_really_inline document_stream::iterator document_stream::end() noexcept {
return iterator(*this, true);
}
simdjson_really_inline document_stream::iterator::iterator(document_stream& _stream, bool is_end) noexcept
: stream{_stream}, finished{is_end} {
}
simdjson_really_inline simdjson_result<element> document_stream::iterator::operator*() noexcept {
// Once we have yielded any errors, we're finished.
if (stream.error) { finished = true; return stream.error; }
return stream.parser->doc.root();
}
simdjson_really_inline document_stream::iterator& document_stream::iterator::operator++() noexcept {
stream.next();
// If that was the last document, we're finished.
if (stream.error == EMPTY) { finished = true; }
return *this;
}
simdjson_really_inline bool document_stream::iterator::operator!=(const document_stream::iterator &other) const noexcept {
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
if (use_thread && 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; }
}
#endif // SIMDJSON_THREADS_ENABLED
next();
}
simdjson_really_inline size_t document_stream::iterator::current_index() const noexcept {
return stream.doc_index;
}
simdjson_really_inline std::string_view document_stream::iterator::source() const noexcept {
size_t next_doc_index = stream.batch_start + stream.parser->implementation->structural_indexes[stream.parser->implementation->next_structural_index];
return std::string_view(reinterpret_cast<const char*>(stream.buf) + current_index(), next_doc_index - current_index() - 1);
}
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
if(use_thread) {
load_from_stage1_thread();
} else {
error = run_stage1(*parser, batch_start);
}
#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
simdjson_really_inline simdjson_result<dom::document_stream>::simdjson_result() noexcept
: simdjson_result_base() {
}
simdjson_really_inline simdjson_result<dom::document_stream>::simdjson_result(error_code error) noexcept
: simdjson_result_base(error) {
}
simdjson_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
simdjson_really_inline dom::document_stream::iterator simdjson_result<dom::document_stream>::begin() noexcept(false) {
if (error()) { throw simdjson_error(error()); }
return first.begin();
}
simdjson_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
simdjson_really_inline dom::document_stream::iterator simdjson_result<dom::document_stream>::begin() noexcept {
first.error = error();
return first.begin();
}
simdjson_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
+290
View File
@@ -0,0 +1,290 @@
#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);
* ```
*/
simdjson_really_inline document_stream() noexcept;
/** Move one document_stream to another. */
simdjson_really_inline document_stream(document_stream &&other) noexcept = default;
/** Move one document_stream to another. */
simdjson_really_inline document_stream &operator=(document_stream &&other) noexcept = default;
simdjson_really_inline ~document_stream() noexcept;
/**
* An iterator through a forward-only stream of documents.
*/
class iterator {
public:
/**
* Get the current document (or error).
*/
simdjson_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.
*/
simdjson_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.
*/
simdjson_really_inline size_t current_index() const noexcept;
/**
* @private
*
* Gives a view of the current document.
*
* document_stream stream = parser.parse_many(json,window);
* for(auto i = stream.begin(); i != stream.end(); ++i) {
* auto doc = *i;
* std::string_view v = i->source();
* }
*
* The returned string_view instance is simply a map to the (unparsed)
* source string: it may thus include white-space characters and all manner
* of padding.
*
* This function (source()) 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.
*/
simdjson_really_inline std::string_view source() const noexcept;
private:
simdjson_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.
*/
simdjson_really_inline iterator begin() noexcept;
/**
* The end of the stream, for iterator comparison purposes.
*/
simdjson_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.
*
* @param parser is a reference to the parser instance used to generate this document_stream
* @param buf is the raw byte buffer we need to process
* @param len is the length of the raw byte buffer in bytes
* @param batch_size is the size of the windows (must be strictly greater or equal to the largest JSON document)
*/
simdjson_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
/** Indicates whether we use threads. Note that this needs to be a constant during the execution of the parsing. */
bool use_thread;
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:
simdjson_really_inline simdjson_result() noexcept; ///< @private
simdjson_really_inline simdjson_result(error_code error) noexcept; ///< @private
simdjson_really_inline simdjson_result(dom::document_stream &&value) noexcept; ///< @private
#if SIMDJSON_EXCEPTIONS
simdjson_really_inline dom::document_stream::iterator begin() noexcept(false);
simdjson_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.")]]
simdjson_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.")]]
simdjson_really_inline dom::document_stream::iterator end() noexcept;
#endif // SIMDJSON_EXCEPTIONS
}; // struct simdjson_result<dom::document_stream>
} // namespace simdjson
#endif // SIMDJSON_DOCUMENT_STREAM_H
+557
View File
@@ -0,0 +1,557 @@
#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
//
simdjson_really_inline simdjson_result<dom::element>::simdjson_result() noexcept
: internal::simdjson_result_base<dom::element>() {}
simdjson_really_inline simdjson_result<dom::element>::simdjson_result(dom::element &&value) noexcept
: internal::simdjson_result_base<dom::element>(std::forward<dom::element>(value)) {}
simdjson_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>
simdjson_really_inline bool simdjson_result<dom::element>::is() const noexcept {
return !error() && first.is<T>();
}
template<typename T>
simdjson_really_inline simdjson_result<T> simdjson_result<dom::element>::get() const noexcept {
if (error()) { return error(); }
return first.get<T>();
}
template<typename T>
SIMDJSON_WARN_UNUSED simdjson_really_inline error_code simdjson_result<dom::element>::get(T &value) const noexcept {
if (error()) { return error(); }
return first.get<T>(value);
}
simdjson_really_inline simdjson_result<dom::array> simdjson_result<dom::element>::get_array() const noexcept {
if (error()) { return error(); }
return first.get_array();
}
simdjson_really_inline simdjson_result<dom::object> simdjson_result<dom::element>::get_object() const noexcept {
if (error()) { return error(); }
return first.get_object();
}
simdjson_really_inline simdjson_result<const char *> simdjson_result<dom::element>::get_c_str() const noexcept {
if (error()) { return error(); }
return first.get_c_str();
}
simdjson_really_inline simdjson_result<size_t> simdjson_result<dom::element>::get_string_length() const noexcept {
if (error()) { return error(); }
return first.get_string_length();
}
simdjson_really_inline simdjson_result<std::string_view> simdjson_result<dom::element>::get_string() const noexcept {
if (error()) { return error(); }
return first.get_string();
}
simdjson_really_inline simdjson_result<int64_t> simdjson_result<dom::element>::get_int64() const noexcept {
if (error()) { return error(); }
return first.get_int64();
}
simdjson_really_inline simdjson_result<uint64_t> simdjson_result<dom::element>::get_uint64() const noexcept {
if (error()) { return error(); }
return first.get_uint64();
}
simdjson_really_inline simdjson_result<double> simdjson_result<dom::element>::get_double() const noexcept {
if (error()) { return error(); }
return first.get_double();
}
simdjson_really_inline simdjson_result<bool> simdjson_result<dom::element>::get_bool() const noexcept {
if (error()) { return error(); }
return first.get_bool();
}
simdjson_really_inline bool simdjson_result<dom::element>::is_array() const noexcept {
return !error() && first.is_array();
}
simdjson_really_inline bool simdjson_result<dom::element>::is_object() const noexcept {
return !error() && first.is_object();
}
simdjson_really_inline bool simdjson_result<dom::element>::is_string() const noexcept {
return !error() && first.is_string();
}
simdjson_really_inline bool simdjson_result<dom::element>::is_int64() const noexcept {
return !error() && first.is_int64();
}
simdjson_really_inline bool simdjson_result<dom::element>::is_uint64() const noexcept {
return !error() && first.is_uint64();
}
simdjson_really_inline bool simdjson_result<dom::element>::is_double() const noexcept {
return !error() && first.is_double();
}
simdjson_really_inline bool simdjson_result<dom::element>::is_bool() const noexcept {
return !error() && first.is_bool();
}
simdjson_really_inline bool simdjson_result<dom::element>::is_null() const noexcept {
return !error() && first.is_null();
}
simdjson_really_inline simdjson_result<dom::element> simdjson_result<dom::element>::operator[](std::string_view key) const noexcept {
if (error()) { return error(); }
return first[key];
}
simdjson_really_inline simdjson_result<dom::element> simdjson_result<dom::element>::operator[](const char *key) const noexcept {
if (error()) { return error(); }
return first[key];
}
simdjson_really_inline simdjson_result<dom::element> simdjson_result<dom::element>::at_pointer(const std::string_view json_pointer) const noexcept {
if (error()) { return error(); }
return first.at_pointer(json_pointer);
}
[[deprecated("For standard compliance, use at_pointer instead, and prefix your pointers with a slash '/', see RFC6901 ")]]
simdjson_really_inline simdjson_result<dom::element> simdjson_result<dom::element>::at(const std::string_view json_pointer) const noexcept {
SIMDJSON_PUSH_DISABLE_WARNINGS
SIMDJSON_DISABLE_DEPRECATED_WARNING
if (error()) { return error(); }
return first.at(json_pointer);
SIMDJSON_POP_DISABLE_WARNINGS
}
simdjson_really_inline simdjson_result<dom::element> simdjson_result<dom::element>::at(size_t index) const noexcept {
if (error()) { return error(); }
return first.at(index);
}
simdjson_really_inline simdjson_result<dom::element> simdjson_result<dom::element>::at_key(std::string_view key) const noexcept {
if (error()) { return error(); }
return first.at_key(key);
}
simdjson_really_inline simdjson_result<dom::element> simdjson_result<dom::element>::at_key_case_insensitive(std::string_view key) const noexcept {
if (error()) { return error(); }
return first.at_key_case_insensitive(key);
}
#if SIMDJSON_EXCEPTIONS
simdjson_really_inline simdjson_result<dom::element>::operator bool() const noexcept(false) {
return get<bool>();
}
simdjson_really_inline simdjson_result<dom::element>::operator const char *() const noexcept(false) {
return get<const char *>();
}
simdjson_really_inline simdjson_result<dom::element>::operator std::string_view() const noexcept(false) {
return get<std::string_view>();
}
simdjson_really_inline simdjson_result<dom::element>::operator uint64_t() const noexcept(false) {
return get<uint64_t>();
}
simdjson_really_inline simdjson_result<dom::element>::operator int64_t() const noexcept(false) {
return get<int64_t>();
}
simdjson_really_inline simdjson_result<dom::element>::operator double() const noexcept(false) {
return get<double>();
}
simdjson_really_inline simdjson_result<dom::element>::operator dom::array() const noexcept(false) {
return get<dom::array>();
}
simdjson_really_inline simdjson_result<dom::element>::operator dom::object() const noexcept(false) {
return get<dom::object>();
}
simdjson_really_inline dom::array::iterator simdjson_result<dom::element>::begin() const noexcept(false) {
if (error()) { throw simdjson_error(error()); }
return first.begin();
}
simdjson_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
//
simdjson_really_inline element::element() noexcept : tape{} {}
simdjson_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(simdjson_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(simdjson_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(simdjson_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>
SIMDJSON_WARN_UNUSED simdjson_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<>
SIMDJSON_WARN_UNUSED simdjson_really_inline error_code element::get<element>(element &value) const noexcept {
value = element(tape);
return SUCCESS;
}
template<typename T>
simdjson_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[](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_pointer(std::string_view json_pointer) const noexcept {
switch (tape.tape_ref_type()) {
case internal::tape_type::START_OBJECT:
return object(tape).at_pointer(json_pointer);
case internal::tape_type::START_ARRAY:
return array(tape).at_pointer(json_pointer);
default: {
if(json_pointer.empty()) { // an empty string means that we return the current node
return INVALID_JSON_POINTER;
}
dom::element copy(*this);
return simdjson_result<element>(std::move(copy));
}
}
}
[[deprecated("For standard compliance, use at_pointer instead, and prefix your pointers with a slash '/', see RFC6901 ")]]
inline simdjson_result<element> element::at(std::string_view json_pointer) const noexcept {
// version 0.4 of simdjson allowed non-compliant pointers
auto std_pointer = (json_pointer.empty() ? "" : "/") + std::string(json_pointer.begin(), json_pointer.end());
return at_pointer(std_pointer);
}
inline simdjson_result<element> element::at(size_t index) const noexcept {
return get<array>().at(index);
}
inline simdjson_result<element> element::at_key(std::string_view key) const noexcept {
return get<object>().at_key(key);
}
inline simdjson_result<element> element::at_key_case_insensitive(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 (simdjson_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 (simdjson_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<>
simdjson_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);
}
simdjson_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
+577
View File
@@ -0,0 +1,577 @@
#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. */
simdjson_really_inline element() noexcept;
/** The type of this element. */
simdjson_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>
simdjson_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>
SIMDJSON_WARN_UNUSED simdjson_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[](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. We use the RFC 6901
* https://tools.ietf.org/html/rfc6901 standard.
*
* dom::parser parser;
* element doc = parser.parse(R"({ "foo": { "a": [ 10, 20, 30 ] }})"_padded);
* doc.at_pointer("/foo/a/1") == 20
* doc.at_pointer("/foo")["a"].at(1) == 20
* doc.at_pointer("")["foo"]["a"].at(1) == 20
*
* It is allowed for a key to be the empty string:
*
* dom::parser parser;
* object obj = parser.parse(R"({ "": { "a": [ 10, 20, 30 ] }})"_padded);
* obj.at_pointer("//a/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_pointer(const std::string_view json_pointer) const noexcept;
/**
*
* Version 0.4 of simdjson used an incorrect interpretation of the JSON Pointer standard
* and allowed the following :
*
* dom::parser parser;
* element doc = parser.parse(R"({ "foo": { "a": [ 10, 20, 30 ] }})"_padded);
* doc.at("foo/a/1") == 20
*
* Though it is intuitive, it is not compliant with RFC 6901
* https://tools.ietf.org/html/rfc6901
*
* For standard compliance, use the at_pointer function instead.
*
* @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
*/
[[deprecated("For standard compliance, use at_pointer instead, and prefix your pointers with a slash '/', see RFC6901 ")]]
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(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(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:
simdjson_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:
simdjson_really_inline simdjson_result() noexcept; ///< @private
simdjson_really_inline simdjson_result(dom::element &&value) noexcept; ///< @private
simdjson_really_inline simdjson_result(error_code error) noexcept; ///< @private
simdjson_really_inline simdjson_result<dom::element_type> type() const noexcept;
template<typename T>
simdjson_really_inline bool is() const noexcept;
template<typename T>
simdjson_really_inline simdjson_result<T> get() const noexcept;
template<typename T>
SIMDJSON_WARN_UNUSED simdjson_really_inline error_code get(T &value) const noexcept;
simdjson_really_inline simdjson_result<dom::array> get_array() const noexcept;
simdjson_really_inline simdjson_result<dom::object> get_object() const noexcept;
simdjson_really_inline simdjson_result<const char *> get_c_str() const noexcept;
simdjson_really_inline simdjson_result<size_t> get_string_length() const noexcept;
simdjson_really_inline simdjson_result<std::string_view> get_string() const noexcept;
simdjson_really_inline simdjson_result<int64_t> get_int64() const noexcept;
simdjson_really_inline simdjson_result<uint64_t> get_uint64() const noexcept;
simdjson_really_inline simdjson_result<double> get_double() const noexcept;
simdjson_really_inline simdjson_result<bool> get_bool() const noexcept;
simdjson_really_inline bool is_array() const noexcept;
simdjson_really_inline bool is_object() const noexcept;
simdjson_really_inline bool is_string() const noexcept;
simdjson_really_inline bool is_int64() const noexcept;
simdjson_really_inline bool is_uint64() const noexcept;
simdjson_really_inline bool is_double() const noexcept;
simdjson_really_inline bool is_bool() const noexcept;
simdjson_really_inline bool is_null() const noexcept;
simdjson_really_inline simdjson_result<dom::element> operator[](std::string_view key) const noexcept;
simdjson_really_inline simdjson_result<dom::element> operator[](const char *key) const noexcept;
simdjson_really_inline simdjson_result<dom::element> at_pointer(const std::string_view json_pointer) const noexcept;
[[deprecated("For standard compliance, use at_pointer instead, and prefix your pointers with a slash '/', see RFC6901 ")]]
simdjson_really_inline simdjson_result<dom::element> at(const std::string_view json_pointer) const noexcept;
simdjson_really_inline simdjson_result<dom::element> at(size_t index) const noexcept;
simdjson_really_inline simdjson_result<dom::element> at_key(std::string_view key) const noexcept;
simdjson_really_inline simdjson_result<dom::element> at_key_case_insensitive(std::string_view key) const noexcept;
#if SIMDJSON_EXCEPTIONS
simdjson_really_inline operator bool() const noexcept(false);
simdjson_really_inline explicit operator const char*() const noexcept(false);
simdjson_really_inline operator std::string_view() const noexcept(false);
simdjson_really_inline operator uint64_t() const noexcept(false);
simdjson_really_inline operator int64_t() const noexcept(false);
simdjson_really_inline operator double() const noexcept(false);
simdjson_really_inline operator dom::array() const noexcept(false);
simdjson_really_inline operator dom::object() const noexcept(false);
simdjson_really_inline dom::array::iterator begin() const noexcept(false);
simdjson_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).
*/
simdjson_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 {
@@ -59,7 +59,7 @@ inline int json_parse(const padded_string &s, dom::parser &parser) noexcept {
}
[[deprecated("Use parser.parse() instead")]]
WARN_UNUSED inline dom::parser build_parsed_json(const uint8_t *buf, size_t len, bool realloc_if_needed = true) noexcept {
SIMDJSON_WARN_UNUSED inline dom::parser build_parsed_json(const uint8_t *buf, size_t len, bool realloc_if_needed = true) noexcept {
dom::parser parser;
error_code code = parser.parse(buf, len, realloc_if_needed).error();
// The deprecated json_parse API is a signal that the user plans to *use* the error code / valid
@@ -71,7 +71,7 @@ WARN_UNUSED inline dom::parser build_parsed_json(const uint8_t *buf, size_t len,
return parser;
}
[[deprecated("Use parser.parse() instead")]]
WARN_UNUSED inline dom::parser build_parsed_json(const char *buf, size_t len, bool realloc_if_needed = true) noexcept {
SIMDJSON_WARN_UNUSED inline dom::parser build_parsed_json(const char *buf, size_t len, bool realloc_if_needed = true) noexcept {
dom::parser parser;
error_code code = parser.parse(buf, len, realloc_if_needed).error();
// The deprecated json_parse API is a signal that the user plans to *use* the error code / valid
@@ -83,7 +83,7 @@ WARN_UNUSED inline dom::parser build_parsed_json(const char *buf, size_t len, bo
return parser;
}
[[deprecated("Use parser.parse() instead")]]
WARN_UNUSED inline dom::parser build_parsed_json(const std::string &s, bool realloc_if_needed = true) noexcept {
SIMDJSON_WARN_UNUSED inline dom::parser build_parsed_json(const std::string &s, bool realloc_if_needed = true) noexcept {
dom::parser parser;
error_code code = parser.parse(s.data(), s.length(), realloc_if_needed).error();
// The deprecated json_parse API is a signal that the user plans to *use* the error code / valid
@@ -95,7 +95,7 @@ WARN_UNUSED inline dom::parser build_parsed_json(const std::string &s, bool real
return parser;
}
[[deprecated("Use parser.parse() instead")]]
WARN_UNUSED inline dom::parser build_parsed_json(const padded_string &s) noexcept {
SIMDJSON_WARN_UNUSED inline dom::parser build_parsed_json(const padded_string &s) noexcept {
dom::parser parser;
error_code code = parser.parse(s).error();
// The deprecated json_parse API is a signal that the user plans to *use* the error code / valid
@@ -114,4 +114,4 @@ dom::parser build_parsed_json(const char *buf) noexcept = delete;
} // namespace simdjson
#endif
#endif // SIMDJSON_DOM_JSONPARSER_H
+293
View File
@@ -0,0 +1,293 @@
#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
//
simdjson_really_inline simdjson_result<dom::object>::simdjson_result() noexcept
: internal::simdjson_result_base<dom::object>() {}
simdjson_really_inline simdjson_result<dom::object>::simdjson_result(dom::object value) noexcept
: internal::simdjson_result_base<dom::object>(std::forward<dom::object>(value)) {}
simdjson_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[](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_pointer(std::string_view json_pointer) const noexcept {
if (error()) { return error(); }
return first.at_pointer(json_pointer);
}
inline simdjson_result<dom::element> simdjson_result<dom::object>::at_key(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(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
//
simdjson_really_inline object::object() noexcept : tape{} {}
simdjson_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[](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_pointer(std::string_view json_pointer) const noexcept {
if(json_pointer[0] != '/') {
if(json_pointer.size() == 0) { // an empty string means that we return the current node
return element(this->tape); // copy the current node
} else { // otherwise there is an error
return INVALID_JSON_POINTER;
}
}
json_pointer = json_pointer.substr(1);
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(child.error()) {
return child; // we do not continue if there was an error
}
// If there is a /, we have to recurse and look up more of the path
if (slash != std::string_view::npos) {
child = child.at_pointer(json_pointer.substr(slash));
}
return child;
}
inline simdjson_result<element> object::at_key(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(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
//
simdjson_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 bool object::iterator::operator==(const object::iterator& other) const noexcept {
return tape.json_index == other.tape.json_index;
}
inline bool object::iterator::operator<(const object::iterator& other) const noexcept {
return tape.json_index < other.tape.json_index;
}
inline bool object::iterator::operator<=(const object::iterator& other) const noexcept {
return tape.json_index <= other.tape.json_index;
}
inline bool object::iterator::operator>=(const object::iterator& other) const noexcept {
return tape.json_index >= other.tape.json_index;
}
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 object::iterator object::iterator::operator++(int) noexcept {
object::iterator out = *this;
++*this;
return out;
}
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(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(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(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
#if defined(__cpp_lib_ranges)
static_assert(std::ranges::view<simdjson::dom::object>);
static_assert(std::ranges::sized_range<simdjson::dom::object>);
#if SIMDJSON_EXCEPTIONS
static_assert(std::ranges::view<simdjson::simdjson_result<simdjson::dom::object>>);
static_assert(std::ranges::sized_range<simdjson::simdjson_result<simdjson::dom::object>>);
#endif // SIMDJSON_EXCEPTIONS
#endif // defined(__cpp_lib_ranges)
#endif // SIMDJSON_INLINE_OBJECT_H
+308
View File
@@ -0,0 +1,308 @@
#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 */
simdjson_really_inline object() noexcept;
class iterator {
public:
using value_type = key_value_pair;
using difference_type = std::ptrdiff_t;
/**
* Get the actual key/value pair
*/
inline const value_type operator*() const noexcept;
/**
* Get the next key/value pair.
*
* Part of the std::iterator interface.
*
*/
inline iterator& operator++() noexcept;
/**
* Get the next key/value pair.
*
* Part of the std::iterator interface.
*
*/
inline iterator operator++(int) 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;
inline bool operator==(const iterator& other) const noexcept;
inline bool operator<(const iterator& other) const noexcept;
inline bool operator<=(const iterator& other) const noexcept;
inline bool operator>=(const iterator& other) const noexcept;
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(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(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;
iterator() noexcept = default;
iterator(const iterator&) noexcept = default;
iterator& operator=(const iterator&) noexcept = default;
private:
simdjson_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[](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. We use the RFC 6901
* https://tools.ietf.org/html/rfc6901 standard, interpreting the current node
* as the root of its own JSON document.
*
* dom::parser parser;
* object obj = parser.parse(R"({ "foo": { "a": [ 10, 20, 30 ] }})"_padded);
* obj.at_pointer("/foo/a/1") == 20
* obj.at_pointer("/foo")["a"].at(1) == 20
*
* It is allowed for a key to be the empty string:
*
* dom::parser parser;
* object obj = parser.parse(R"({ "": { "a": [ 10, 20, 30 ] }})"_padded);
* obj.at_pointer("//a/1") == 20
* obj.at_pointer("/")["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_pointer(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(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(std::string_view key) const noexcept;
private:
simdjson_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:
simdjson_really_inline key_value_pair(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:
simdjson_really_inline simdjson_result() noexcept; ///< @private
simdjson_really_inline simdjson_result(dom::object value) noexcept; ///< @private
simdjson_really_inline simdjson_result(error_code error) noexcept; ///< @private
inline simdjson_result<dom::element> operator[](std::string_view key) const noexcept;
inline simdjson_result<dom::element> operator[](const char *key) const noexcept;
inline simdjson_result<dom::element> at_pointer(std::string_view json_pointer) const noexcept;
inline simdjson_result<dom::element> at_key(std::string_view key) const noexcept;
inline simdjson_result<dom::element> at_key_case_insensitive(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
#if defined(__cpp_lib_ranges)
#include <ranges>
namespace std {
namespace ranges {
template<>
inline constexpr bool enable_view<simdjson::dom::object> = true;
#if SIMDJSON_EXCEPTIONS
template<>
inline constexpr bool enable_view<simdjson::simdjson_result<simdjson::dom::object>> = true;
#endif // SIMDJSON_EXCEPTIONS
} // namespace ranges
} // namespace std
#endif // defined(__cpp_lib_ranges)
#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
@@ -1,13 +1,19 @@
#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 {
SIMDJSON_WARN_UNUSED bool dom::parser::Iterator::is_ok() const {
return location < tape_length;
}
@@ -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

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