diff --git a/deps/simdjson/simdjson.cpp b/deps/simdjson/simdjson.cpp index 537a7ab6a9a5..e19b8c9e5f7a 100644 --- a/deps/simdjson/simdjson.cpp +++ b/deps/simdjson/simdjson.cpp @@ -1,4 +1,4 @@ -/* auto-generated on 2026-11-14 18:54:03 -0500. version 5.2.0 Do not edit! */ +/* auto-generated on 2026-11-22 13:48:29 -0500. version 5.3.0 Do not edit! */ /* including simdjson.cpp: */ /* begin file simdjson.cpp */ #define SIMDJSON_SRC_SIMDJSON_CPP @@ -622,10 +622,9 @@ namespace internal { * @private * Scratch capacity that every caller of to_chars must provide. * - * The emitted decimal is at most ~24 characters, but dragonbox() and - * format_buffer() intentionally write past the logical end with fixed-size - * 16/17-byte memcpy/memset operations so the compiler can inline them (no - * libc mem* dispatch with size-class branches). The extra bytes are required + * The emitted decimal is at most ~24 characters, but to_chars() intentionally + * writes past the logical end with fixed-size 8- and 16-byte stores, so that + * the layout needs no length-dependent branches. The extra bytes are required * for safety of those over-writes; do not shrink this below 40. * See src/to_chars.cpp and #2805. */ @@ -672,6 +671,10 @@ float from_chars_float(const char *first) noexcept; #define SIMDJSON_ENABLE_NAN_INF 0 #endif +#ifndef SIMDJSON_ALLOW_TRAILING_COMMAS +#define SIMDJSON_ALLOW_TRAILING_COMMAS 0 +#endif + } // namespace simdjson #if defined(__GNUC__) @@ -2719,6 +2722,25 @@ namespace std { #else #define simdjson_lifetime_bound #endif + +// C++26 (P2795R5) and -ftrivial-auto-var-init zero-fill local variables that +// have no initializer. simdjson_indeterminate opts a local out of that. Use it +// only on buffers that the code writes before it reads them. +#if defined(SIMDJSON_CPLUSPLUS26) && defined(__has_cpp_attribute) +#if __has_cpp_attribute(indeterminate) +#define simdjson_indeterminate [[indeterminate]] +#endif +#endif + +#if !defined(simdjson_indeterminate) && defined(__has_attribute) +#if __has_attribute(uninitialized) +#define simdjson_indeterminate __attribute__((uninitialized)) +#endif +#endif + +#ifndef simdjson_indeterminate +#define simdjson_indeterminate +#endif #endif // SIMDJSON_COMMON_DEFS_H /* end file simdjson/common_defs.h */ /* skipped duplicate #include "simdjson/compiler_check.h" */ @@ -3054,6 +3076,22 @@ struct simdjson_result : public internal::simdjson_result_base { return error; } + /** + * Provide a default value for a missing key. + * + * If the error is NO_SUCH_FIELD, returns a successful result holding default_value. + * Otherwise, returns this result unchanged: the value, or any other error + * (e.g., INCORRECT_TYPE, TAPE_ERROR) which is still reported. + * + * double z = obj["z"].get_double().default_if_missing(0.0); + * // or, without exceptions: + * double z; + * auto error = obj["z"].get_double().default_if_missing(0.0).get(z); + * + * @param default_value The value to use when the key is missing. + */ + simdjson_warn_unused simdjson_inline simdjson_result default_if_missing(T default_value) && noexcept; + /** * The error. */ @@ -3621,1148 +3659,995 @@ SIMDJSON_PUSH_DISABLE_UNUSED_WARNINGS #include #include -#include -#include +#include + +#if defined(_MSC_VER) && !defined(__clang__) +#include +#endif + +#if defined(__aarch64__) && !SIMDJSON_IS_BIG_ENDIAN && \ + (defined(__GNUC__) || defined(__clang__)) +#define SIMDJSON_TO_CHARS_NEON 1 +#include +#else +#define SIMDJSON_TO_CHARS_NEON 0 +#endif namespace simdjson { namespace internal { /*! -Implements the Dragonbox algorithm for binary to decimal floating-point -conversion (shortest round-trip representation of a double). +Shortest round-trip conversion of a binary64 double to decimal text. -The digit-generation core below is a self-contained port of Junekey Jeon's -reference "simple_dragonbox" implementation, specialized to IEEE-754 binary64 -and de-templated to match simdjson's style. Only the shortest-representation -path with the default (nearest, ties-to-even) rounding is kept. +The digit-generation core is a port of Victor Zverovich's Zmij, specialized to +IEEE-754 binary64 and reduced to C++11: -Dragonbox: https://github.com/jk-jeon/dragonbox -Copyright 2020-2025 Junekey Jeon (and contributors). +Zmij: https://github.com/vitaut/zmij +Copyright (c) 2025 - present, Victor Zverovich +Distributed under the MIT license or, alternatively, the Boost Software +License, Version 1.0 (https://www.boost.org/LICENSE_1_0.txt). -The original is dual-licensed; this port is used under the terms of the -Boost Software License, Version 1.0 (https://www.boost.org/LICENSE_1_0.txt). +Zmij is based on Schubfach and on Xiang JunBo's yy/xjb, and its correctness +(shortest output, correct rounding) is proved in Lean in the upstream +repository. The produced digits are the same as those of Ryu or Dragonbox. -For the algorithm itself see: -[1] Junekey Jeon, "Dragonbox: A New Floating-Point Binary-to-Decimal Conversion Algorithm" (2022). - -The shortest decimal digits produced here are then laid out into the familiar -printf("%g")-style text by format_buffer(), which is unchanged from the previous -Grisu2-based implementation, so the emitted strings are identical except that -Dragonbox always yields the (sometimes shorter) shortest representation. +The digits are laid out into the printf("%g")-style text simdjson has always +emitted (for example "1.5", "123.0", "0.001", "1e+20", "1.5e-07"). */ namespace dtoa_impl { -// 128-bit helpers (no compiler intrinsics, so the code stays portable). struct uint128 { - std::uint64_t high; - std::uint64_t low; + std::uint64_t hi; + std::uint64_t lo; }; -inline std::uint64_t rotr64(std::uint64_t n, unsigned r) noexcept { - r &= 63; - return (n >> r) | (n << ((64 - r) & 63)); -} - -inline std::uint64_t umul64(std::uint32_t x, std::uint32_t y) noexcept { - return x * std::uint64_t(y); -} - -// 64x64 -> 128 bit multiplication. -inline uint128 umul128(std::uint64_t x, std::uint64_t y) noexcept { +simdjson_really_inline uint128 umul128(std::uint64_t x, std::uint64_t y) noexcept { #if defined(__SIZEOF_INT128__) - const __uint128_t p = static_cast<__uint128_t>(x)*y; - return {std::uint64_t(p>>64), std::uint64_t(p)}; -#else // using fallback on 32-bit targets and MSVC - const std::uint32_t a = std::uint32_t(x >> 32); - const std::uint32_t b = std::uint32_t(x); - const std::uint32_t c = std::uint32_t(y >> 32); - const std::uint32_t d = std::uint32_t(y); - - const std::uint64_t ac = umul64(a, c); - const std::uint64_t bc = umul64(b, c); - const std::uint64_t ad = umul64(a, d); - const std::uint64_t bd = umul64(b, d); - - const std::uint64_t intermediate = - (bd >> 32) + std::uint32_t(ad) + std::uint32_t(bc); - - return {ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32), - (intermediate << 32) + std::uint32_t(bd)}; -#endif -} - -// High 64 bits of a 64x64 -> 128 bit multiplication. -inline std::uint64_t umul128_upper64(std::uint64_t x, std::uint64_t y) noexcept { -#if defined(__SIZEOF_INT128__) - return std::uint64_t((static_cast<__uint128_t>(x)*y)>>64); -#else // using fallback on 32-bit targets and MSVC - const std::uint32_t a = std::uint32_t(x >> 32); - const std::uint32_t b = std::uint32_t(x); - const std::uint32_t c = std::uint32_t(y >> 32); - const std::uint32_t d = std::uint32_t(y); - - const std::uint64_t ac = umul64(a, c); - const std::uint64_t bc = umul64(b, c); - const std::uint64_t ad = umul64(a, d); - const std::uint64_t bd = umul64(b, d); - - const std::uint64_t intermediate = - (bd >> 32) + std::uint32_t(ad) + std::uint32_t(bc); - - return ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32); -#endif -} - -// Upper 128 bits of a 64 x 128 -> 192 bit multiplication. -inline uint128 umul192_upper128(std::uint64_t x, uint128 y) noexcept { - uint128 r = umul128(x, y.high); - const std::uint64_t add = umul128_upper64(x, y.low); - const std::uint64_t sum = r.low + add; - r.high += (sum < r.low) ? 1 : 0; - r.low = sum; - return r; -} - -// Lower 128 bits of a 64 x 128 -> 192 bit multiplication. -inline uint128 umul192_lower128(std::uint64_t x, uint128 y) noexcept { - const std::uint64_t high = x * y.high; - const uint128 high_low = umul128(x, y.low); - return {high + high_low.high, high_low.low}; -} - -// Integer log approximations (exact over the range of inputs we feed them). -inline int floor_log10_pow2(int e) noexcept { return (e * 315653) >> 20; } -inline int floor_log2_pow10(int e) noexcept { return (e * 1741647) >> 19; } -inline int floor_log10_pow2_minus_log10_4_over_3(int e) noexcept { - return (e * 631305 - 261663) >> 21; -} - -// Format constants for IEEE-754 binary64, plus the precomputed cache of powers of ten. -static constexpr int kappa = 2; -static constexpr int significand_bits = 52; -static constexpr int total_bits = 64; -static constexpr int min_exponent = -1022; -static constexpr int exponent_bias = -1023; -static constexpr int cache_min_k = -292; -static constexpr int big_divisor = 1000; // 10^(kappa + 1) -static constexpr int small_divisor = 100; // 10^kappa -static constexpr int case_shorter_interval_left_endpoint_lower_threshold = 2; -static constexpr int case_shorter_interval_left_endpoint_upper_threshold = 3; -static constexpr int shorter_interval_tie_lower_threshold = -77; -static constexpr int shorter_interval_tie_upper_threshold = -77; - -// cache[i] holds a 128-bit approximation of a power of ten; indexed by -// (-minus_k - cache_min_k). Taken verbatim from the Dragonbox reference. -static constexpr uint128 cache[619] = { - {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b}, - {0x9faacf3df73609b1, 0x77b191618c54e9ad}, - {0xc795830d75038c1d, 0xd59df5b9ef6a2418}, - {0xf97ae3d0d2446f25, 0x4b0573286b44ad1e}, - {0x9becce62836ac577, 0x4ee367f9430aec33}, - {0xc2e801fb244576d5, 0x229c41f793cda740}, - {0xf3a20279ed56d48a, 0x6b43527578c11110}, - {0x9845418c345644d6, 0x830a13896b78aaaa}, - {0xbe5691ef416bd60c, 0x23cc986bc656d554}, - {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa9}, - {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6aa}, - {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc54}, - {0xe858ad248f5c22c9, 0xd1b3400f8f9cff69}, - {0x91376c36d99995be, 0x23100809b9c21fa2}, - {0xb58547448ffffb2d, 0xabd40a0c2832a78b}, - {0xe2e69915b3fff9f9, 0x16c90c8f323f516d}, - {0x8dd01fad907ffc3b, 0xae3da7d97f6792e4}, - {0xb1442798f49ffb4a, 0x99cd11cfdf41779d}, - {0xdd95317f31c7fa1d, 0x40405643d711d584}, - {0x8a7d3eef7f1cfc52, 0x482835ea666b2573}, - {0xad1c8eab5ee43b66, 0xda3243650005eed0}, - {0xd863b256369d4a40, 0x90bed43e40076a83}, - {0x873e4f75e2224e68, 0x5a7744a6e804a292}, - {0xa90de3535aaae202, 0x711515d0a205cb37}, - {0xd3515c2831559a83, 0x0d5a5b44ca873e04}, - {0x8412d9991ed58091, 0xe858790afe9486c3}, - {0xa5178fff668ae0b6, 0x626e974dbe39a873}, - {0xce5d73ff402d98e3, 0xfb0a3d212dc81290}, - {0x80fa687f881c7f8e, 0x7ce66634bc9d0b9a}, - {0xa139029f6a239f72, 0x1c1fffc1ebc44e81}, - {0xc987434744ac874e, 0xa327ffb266b56221}, - {0xfbe9141915d7a922, 0x4bf1ff9f0062baa9}, - {0x9d71ac8fada6c9b5, 0x6f773fc3603db4aa}, - {0xc4ce17b399107c22, 0xcb550fb4384d21d4}, - {0xf6019da07f549b2b, 0x7e2a53a146606a49}, - {0x99c102844f94e0fb, 0x2eda7444cbfc426e}, - {0xc0314325637a1939, 0xfa911155fefb5309}, - {0xf03d93eebc589f88, 0x793555ab7eba27cb}, - {0x96267c7535b763b5, 0x4bc1558b2f3458df}, - {0xbbb01b9283253ca2, 0x9eb1aaedfb016f17}, - {0xea9c227723ee8bcb, 0x465e15a979c1cadd}, - {0x92a1958a7675175f, 0x0bfacd89ec191eca}, - {0xb749faed14125d36, 0xcef980ec671f667c}, - {0xe51c79a85916f484, 0x82b7e12780e7401b}, - {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908811}, - {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa16}, - {0xdfbdcece67006ac9, 0x67a791e093e1d49b}, - {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e1}, - {0xaecc49914078536d, 0x58fae9f773886e19}, - {0xda7f5bf590966848, 0xaf39a475506a899f}, - {0x888f99797a5e012d, 0x6d8406c952429604}, - {0xaab37fd7d8f58178, 0xc8e5087ba6d33b84}, - {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a65}, - {0x855c3be0a17fcd26, 0x5cf2eea09a550680}, - {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f}, - {0xd0601d8efc57b08b, 0xf13b94daf124da27}, - {0x823c12795db6ce57, 0x76c53d08d6b70859}, - {0xa2cb1717b52481ed, 0x54768c4b0c64ca6f}, - {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd0a}, - {0xfe5d54150b090b02, 0xd3f93b35435d7c4d}, - {0x9efa548d26e5a6e1, 0xc47bc5014a1a6db0}, - {0xc6b8e9b0709f109a, 0x359ab6419ca1091c}, - {0xf867241c8cc6d4c0, 0xc30163d203c94b63}, - {0x9b407691d7fc44f8, 0x79e0de63425dcf1e}, - {0xc21094364dfb5636, 0x985915fc12f542e5}, - {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939e}, - {0x979cf3ca6cec5b5a, 0xa705992ceecf9c43}, - {0xbd8430bd08277231, 0x50c6ff782a838354}, - {0xece53cec4a314ebd, 0xa4f8bf5635246429}, - {0x940f4613ae5ed136, 0x871b7795e136be9a}, - {0xb913179899f68584, 0x28e2557b59846e40}, - {0xe757dd7ec07426e5, 0x331aeada2fe589d0}, - {0x9096ea6f3848984f, 0x3ff0d2c85def7622}, - {0xb4bca50b065abe63, 0x0fed077a756b53aa}, - {0xe1ebce4dc7f16dfb, 0xd3e8495912c62895}, - {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95d}, - {0xb080392cc4349dec, 0xbd8d794d96aacfb4}, - {0xdca04777f541c567, 0xecf0d7a0fc5583a1}, - {0x89e42caaf9491b60, 0xf41686c49db57245}, - {0xac5d37d5b79b6239, 0x311c2875c522ced6}, - {0xd77485cb25823ac7, 0x7d633293366b828c}, - {0x86a8d39ef77164bc, 0xae5dff9c02033198}, - {0xa8530886b54dbdeb, 0xd9f57f830283fdfd}, - {0xd267caa862a12d66, 0xd072df63c324fd7c}, - {0x8380dea93da4bc60, 0x4247cb9e59f71e6e}, - {0xa46116538d0deb78, 0x52d9be85f074e609}, - {0xcd795be870516656, 0x67902e276c921f8c}, - {0x806bd9714632dff6, 0x00ba1cd8a3db53b7}, - {0xa086cfcd97bf97f3, 0x80e8a40eccd228a5}, - {0xc8a883c0fdaf7df0, 0x6122cd128006b2ce}, - {0xfad2a4b13d1b5d6c, 0x796b805720085f82}, - {0x9cc3a6eec6311a63, 0xcbe3303674053bb1}, - {0xc3f490aa77bd60fc, 0xbedbfc4411068a9d}, - {0xf4f1b4d515acb93b, 0xee92fb5515482d45}, - {0x991711052d8bf3c5, 0x751bdd152d4d1c4b}, - {0xbf5cd54678eef0b6, 0xd262d45a78a0635e}, - {0xef340a98172aace4, 0x86fb897116c87c35}, - {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da1}, - {0xbae0a846d2195712, 0x8974836059cca10a}, - {0xe998d258869facd7, 0x2bd1a438703fc94c}, - {0x91ff83775423cc06, 0x7b6306a34627ddd0}, - {0xb67f6455292cbf08, 0x1a3bc84c17b1d543}, - {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a94}, - {0x8e938662882af53e, 0x547eb47b7282ee9d}, - {0xb23867fb2a35b28d, 0xe99e619a4f23aa44}, - {0xdec681f9f4c31f31, 0x6405fa00e2ec94d5}, - {0x8b3c113c38f9f37e, 0xde83bc408dd3dd05}, - {0xae0b158b4738705e, 0x9624ab50b148d446}, - {0xd98ddaee19068c76, 0x3badd624dd9b0958}, - {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d7}, - {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4d}, - {0xd47487cc8470652b, 0x7647c32000696720}, - {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e074}, - {0xa5fb0a17c777cf09, 0xf468107100525891}, - {0xcf79cc9db955c2cc, 0x7182148d4066eeb5}, - {0x81ac1fe293d599bf, 0xc6f14cd848405531}, - {0xa21727db38cb002f, 0xb8ada00e5a506a7d}, - {0xca9cf1d206fdc03b, 0xa6d90811f0e4851d}, - {0xfd442e4688bd304a, 0x908f4a166d1da664}, - {0x9e4a9cec15763e2e, 0x9a598e4e043287ff}, - {0xc5dd44271ad3cdba, 0x40eff1e1853f29fe}, - {0xf7549530e188c128, 0xd12bee59e68ef47d}, - {0x9a94dd3e8cf578b9, 0x82bb74f8301958cf}, - {0xc13a148e3032d6e7, 0xe36a52363c1faf02}, - {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac2}, - {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0ba}, - {0xbcb2b812db11a5de, 0x7415d448f6b6f0e8}, - {0xebdf661791d60f56, 0x111b495b3464ad22}, - {0x936b9fcebb25c995, 0xcab10dd900beec35}, - {0xb84687c269ef3bfb, 0x3d5d514f40eea743}, - {0xe65829b3046b0afa, 0x0cb4a5a3112a5113}, - {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ac}, - {0xb3f4e093db73a093, 0x59ed216765690f57}, - {0xe0f218b8d25088b8, 0x306869c13ec3532d}, - {0x8c974f7383725573, 0x1e414218c73a13fc}, - {0xafbd2350644eeacf, 0xe5d1929ef90898fb}, - {0xdbac6c247d62a583, 0xdf45f746b74abf3a}, - {0x894bc396ce5da772, 0x6b8bba8c328eb784}, - {0xab9eb47c81f5114f, 0x066ea92f3f326565}, - {0xd686619ba27255a2, 0xc80a537b0efefebe}, - {0x8613fd0145877585, 0xbd06742ce95f5f37}, - {0xa798fc4196e952e7, 0x2c48113823b73705}, - {0xd17f3b51fca3a7a0, 0xf75a15862ca504c6}, - {0x82ef85133de648c4, 0x9a984d73dbe722fc}, - {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebbb}, - {0xcc963fee10b7d1b3, 0x318df905079926a9}, - {0xffbbcfe994e5c61f, 0xfdf17746497f7053}, - {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa634}, - {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc1}, - {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b1}, - {0x9c1661a651213e2d, 0x06bea10ca65c084f}, - {0xc31bfa0fe5698db8, 0x486e494fcff30a63}, - {0xf3e2f893dec3f126, 0x5a89dba3c3efccfb}, - {0x986ddb5c6b3a76b7, 0xf89629465a75e01d}, - {0xbe89523386091465, 0xf6bbb397f1135824}, - {0xee2ba6c0678b597f, 0x746aa07ded582e2d}, - {0x94db483840b717ef, 0xa8c2a44eb4571cdd}, - {0xba121a4650e4ddeb, 0x92f34d62616ce414}, - {0xe896a0d7e51e1566, 0x77b020baf9c81d18}, - {0x915e2486ef32cd60, 0x0ace1474dc1d122f}, - {0xb5b5ada8aaff80b8, 0x0d819992132456bb}, - {0xe3231912d5bf60e6, 0x10e1fff697ed6c6a}, - {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2}, - {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb3}, - {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbdf}, - {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96c}, - {0xad4ab7112eb3929d, 0x86c16c98d2c953c7}, - {0xd89d64d57a607744, 0xe871c7bf077ba8b8}, - {0x87625f056c7c4a8b, 0x11471cd764ad4973}, - {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bd0}, - {0xd389b47879823479, 0x4aff1d108d4ec2c4}, - {0x843610cb4bf160cb, 0xcedf722a585139bb}, - {0xa54394fe1eedb8fe, 0xc2974eb4ee658829}, - {0xce947a3da6a9273e, 0x733d226229feea33}, - {0x811ccc668829b887, 0x0806357d5a3f5260}, - {0xa163ff802a3426a8, 0xca07c2dcb0cf26f8}, - {0xc9bcff6034c13052, 0xfc89b393dd02f0b6}, - {0xfc2c3f3841f17c67, 0xbbac2078d443ace3}, - {0x9d9ba7832936edc0, 0xd54b944b84aa4c0e}, - {0xc5029163f384a931, 0x0a9e795e65d4df12}, - {0xf64335bcf065d37d, 0x4d4617b5ff4a16d6}, - {0x99ea0196163fa42e, 0x504bced1bf8e4e46}, - {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d7}, - {0xf07da27a82c37088, 0x5d767327bb4e5a4d}, - {0x964e858c91ba2655, 0x3a6a07f8d510f870}, - {0xbbe226efb628afea, 0x890489f70a55368c}, - {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842f}, - {0x92c8ae6b464fc96f, 0x3b0b8bc90012929e}, - {0xb77ada0617e3bbcb, 0x09ce6ebb40173745}, - {0xe55990879ddcaabd, 0xcc420a6a101d0516}, - {0x8f57fa54c2a9eab6, 0x9fa946824a12232e}, - {0xb32df8e9f3546564, 0x47939822dc96abfa}, - {0xdff9772470297ebd, 0x59787e2b93bc56f8}, - {0x8bfbea76c619ef36, 0x57eb4edb3c55b65b}, - {0xaefae51477a06b03, 0xede622920b6b23f2}, - {0xdab99e59958885c4, 0xe95fab368e45ecee}, - {0x88b402f7fd75539b, 0x11dbcb0218ebb415}, - {0xaae103b5fcd2a881, 0xd652bdc29f26a11a}, - {0xd59944a37c0752a2, 0x4be76d3346f04960}, - {0x857fcae62d8493a5, 0x6f70a4400c562ddc}, - {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb953}, - {0xd097ad07a71f26b2, 0x7e2000a41346a7a8}, - {0x825ecc24c873782f, 0x8ed400668c0c28c9}, - {0xa2f67f2dfa90563b, 0x728900802f0f32fb}, - {0xcbb41ef979346bca, 0x4f2b40a03ad2ffba}, - {0xfea126b7d78186bc, 0xe2f610c84987bfa9}, - {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7ca}, - {0xc6ede63fa05d3143, 0x91503d1c79720dbc}, - {0xf8a95fcf88747d94, 0x75a44c6397ce912b}, - {0x9b69dbe1b548ce7c, 0xc986afbe3ee11abb}, - {0xc24452da229b021b, 0xfbe85badce996169}, - {0xf2d56790ab41c2a2, 0xfae27299423fb9c4}, - {0x97c560ba6b0919a5, 0xdccd879fc967d41b}, - {0xbdb6b8e905cb600f, 0x5400e987bbc1c921}, - {0xed246723473e3813, 0x290123e9aab23b69}, - {0x9436c0760c86e30b, 0xf9a0b6720aaf6522}, - {0xb94470938fa89bce, 0xf808e40e8d5b3e6a}, - {0xe7958cb87392c2c2, 0xb60b1d1230b20e05}, - {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c3}, - {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af4}, - {0xe2280b6c20dd5232, 0x25c6da63c38de1b1}, - {0x8d590723948a535f, 0x579c487e5a38ad0f}, - {0xb0af48ec79ace837, 0x2d835a9df0c6d852}, - {0xdcdb1b2798182244, 0xf8e431456cf88e66}, - {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b5900}, - {0xac8b2d36eed2dac5, 0xe272467e3d222f40}, - {0xd7adf884aa879177, 0x5b0ed81dcc6abb10}, - {0x86ccbb52ea94baea, 0x98e947129fc2b4ea}, - {0xa87fea27a539e9a5, 0x3f2398d747b36225}, - {0xd29fe4b18e88640e, 0x8eec7f0d19a03aae}, - {0x83a3eeeef9153e89, 0x1953cf68300424ad}, - {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd8}, - {0xcdb02555653131b6, 0x3792f412cb06794e}, - {0x808e17555f3ebf11, 0xe2bbd88bbee40bd1}, - {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec5}, - {0xc8de047564d20a8b, 0xf245825a5a445276}, - {0xfb158592be068d2e, 0xeed6e2f0f0d56713}, - {0x9ced737bb6c4183d, 0x55464dd69685606c}, - {0xc428d05aa4751e4c, 0xaa97e14c3c26b887}, - {0xf53304714d9265df, 0xd53dd99f4b3066a9}, - {0x993fe2c6d07b7fab, 0xe546a8038efe402a}, - {0xbf8fdb78849a5f96, 0xde98520472bdd034}, - {0xef73d256a5c0f77c, 0x963e66858f6d4441}, - {0x95a8637627989aad, 0xdde7001379a44aa9}, - {0xbb127c53b17ec159, 0x5560c018580d5d53}, - {0xe9d71b689dde71af, 0xaab8f01e6e10b4a7}, - {0x9226712162ab070d, 0xcab3961304ca70e9}, - {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d23}, - {0xe45c10c42a2b3b05, 0x8cb89a7db77c506b}, - {0x8eb98a7a9a5b04e3, 0x77f3608e92adb243}, - {0xb267ed1940f1c61c, 0x55f038b237591ed4}, - {0xdf01e85f912e37a3, 0x6b6c46dec52f6689}, - {0x8b61313bbabce2c6, 0x2323ac4b3b3da016}, - {0xae397d8aa96c1b77, 0xabec975e0a0d081b}, - {0xd9c7dced53c72255, 0x96e7bd358c904a22}, - {0x881cea14545c7575, 0x7e50d64177da2e55}, - {0xaa242499697392d2, 0xdde50bd1d5d0b9ea}, - {0xd4ad2dbfc3d07787, 0x955e4ec64b44e865}, - {0x84ec3c97da624ab4, 0xbd5af13bef0b113f}, - {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58f}, - {0xcfb11ead453994ba, 0x67de18eda5814af3}, - {0x81ceb32c4b43fcf4, 0x80eacf948770ced8}, - {0xa2425ff75e14fc31, 0xa1258379a94d028e}, - {0xcad2f7f5359a3b3e, 0x096ee45813a04331}, - {0xfd87b5f28300ca0d, 0x8bca9d6e188853fd}, - {0x9e74d1b791e07e48, 0x775ea264cf55347e}, - {0xc612062576589dda, 0x95364afe032a819e}, - {0xf79687aed3eec551, 0x3a83ddbd83f52205}, - {0x9abe14cd44753b52, 0xc4926a9672793543}, - {0xc16d9a0095928a27, 0x75b7053c0f178294}, - {0xf1c90080baf72cb1, 0x5324c68b12dd6339}, - {0x971da05074da7bee, 0xd3f6fc16ebca5e04}, - {0xbce5086492111aea, 0x88f4bb1ca6bcf585}, - {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6}, - {0x9392ee8e921d5d07, 0x3aff322e62439fd0}, - {0xb877aa3236a4b449, 0x09befeb9fad487c3}, - {0xe69594bec44de15b, 0x4c2ebe687989a9b4}, - {0x901d7cf73ab0acd9, 0x0f9d37014bf60a11}, - {0xb424dc35095cd80f, 0x538484c19ef38c95}, - {0xe12e13424bb40e13, 0x2865a5f206b06fba}, - {0x8cbccc096f5088cb, 0xf93f87b7442e45d4}, - {0xafebff0bcb24aafe, 0xf78f69a51539d749}, - {0xdbe6fecebdedd5be, 0xb573440e5a884d1c}, - {0x89705f4136b4a597, 0x31680a88f8953031}, - {0xabcc77118461cefc, 0xfdc20d2b36ba7c3e}, - {0xd6bf94d5e57a42bc, 0x3d32907604691b4d}, - {0x8637bd05af6c69b5, 0xa63f9a49c2c1b110}, - {0xa7c5ac471b478423, 0x0fcf80dc33721d54}, - {0xd1b71758e219652b, 0xd3c36113404ea4a9}, - {0x83126e978d4fdf3b, 0x645a1cac083126ea}, - {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4}, - {0xcccccccccccccccc, 0xcccccccccccccccd}, - {0x8000000000000000, 0x0000000000000000}, - {0xa000000000000000, 0x0000000000000000}, - {0xc800000000000000, 0x0000000000000000}, - {0xfa00000000000000, 0x0000000000000000}, - {0x9c40000000000000, 0x0000000000000000}, - {0xc350000000000000, 0x0000000000000000}, - {0xf424000000000000, 0x0000000000000000}, - {0x9896800000000000, 0x0000000000000000}, - {0xbebc200000000000, 0x0000000000000000}, - {0xee6b280000000000, 0x0000000000000000}, - {0x9502f90000000000, 0x0000000000000000}, - {0xba43b74000000000, 0x0000000000000000}, - {0xe8d4a51000000000, 0x0000000000000000}, - {0x9184e72a00000000, 0x0000000000000000}, - {0xb5e620f480000000, 0x0000000000000000}, - {0xe35fa931a0000000, 0x0000000000000000}, - {0x8e1bc9bf04000000, 0x0000000000000000}, - {0xb1a2bc2ec5000000, 0x0000000000000000}, - {0xde0b6b3a76400000, 0x0000000000000000}, - {0x8ac7230489e80000, 0x0000000000000000}, - {0xad78ebc5ac620000, 0x0000000000000000}, - {0xd8d726b7177a8000, 0x0000000000000000}, - {0x878678326eac9000, 0x0000000000000000}, - {0xa968163f0a57b400, 0x0000000000000000}, - {0xd3c21bcecceda100, 0x0000000000000000}, - {0x84595161401484a0, 0x0000000000000000}, - {0xa56fa5b99019a5c8, 0x0000000000000000}, - {0xcecb8f27f4200f3a, 0x0000000000000000}, - {0x813f3978f8940984, 0x4000000000000000}, - {0xa18f07d736b90be5, 0x5000000000000000}, - {0xc9f2c9cd04674ede, 0xa400000000000000}, - {0xfc6f7c4045812296, 0x4d00000000000000}, - {0x9dc5ada82b70b59d, 0xf020000000000000}, - {0xc5371912364ce305, 0x6c28000000000000}, - {0xf684df56c3e01bc6, 0xc732000000000000}, - {0x9a130b963a6c115c, 0x3c7f400000000000}, - {0xc097ce7bc90715b3, 0x4b9f100000000000}, - {0xf0bdc21abb48db20, 0x1e86d40000000000}, - {0x96769950b50d88f4, 0x1314448000000000}, - {0xbc143fa4e250eb31, 0x17d955a000000000}, - {0xeb194f8e1ae525fd, 0x5dcfab0800000000}, - {0x92efd1b8d0cf37be, 0x5aa1cae500000000}, - {0xb7abc627050305ad, 0xf14a3d9e40000000}, - {0xe596b7b0c643c719, 0x6d9ccd05d0000000}, - {0x8f7e32ce7bea5c6f, 0xe4820023a2000000}, - {0xb35dbf821ae4f38b, 0xdda2802c8a800000}, - {0xe0352f62a19e306e, 0xd50b2037ad200000}, - {0x8c213d9da502de45, 0x4526f422cc340000}, - {0xaf298d050e4395d6, 0x9670b12b7f410000}, - {0xdaf3f04651d47b4c, 0x3c0cdd765f114000}, - {0x88d8762bf324cd0f, 0xa5880a69fb6ac800}, - {0xab0e93b6efee0053, 0x8eea0d047a457a00}, - {0xd5d238a4abe98068, 0x72a4904598d6d880}, - {0x85a36366eb71f041, 0x47a6da2b7f864750}, - {0xa70c3c40a64e6c51, 0x999090b65f67d924}, - {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d}, - {0x82818f1281ed449f, 0xbff8f10e7a8921a5}, - {0xa321f2d7226895c7, 0xaff72d52192b6a0e}, - {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764491}, - {0xfee50b7025c36a08, 0x02f236d04753d5b5}, - {0x9f4f2726179a2245, 0x01d762422c946591}, - {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef6}, - {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb3}, - {0x9b934c3b330c8577, 0x63cc55f49f88eb30}, - {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fc}, - {0xf316271c7fc3908a, 0x8bef464e3945ef7b}, - {0x97edd871cfda3a56, 0x97758bf0e3cbb5ad}, - {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea318}, - {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bde}, - {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6b}, - {0xb975d6b6ee39e436, 0xb3e2fd538e122b45}, - {0xe7d34c64a9c85d44, 0x60dbbca87196b617}, - {0x90e40fbeea1d3a4a, 0xbc8955e946fe31ce}, - {0xb51d13aea4a488dd, 0x6babab6398bdbe42}, - {0xe264589a4dcdab14, 0xc696963c7eed2dd2}, - {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca3}, - {0xb0de65388cc8ada8, 0x3b25a55f43294bcc}, - {0xdd15fe86affad912, 0x49ef0eb713f39ebf}, - {0x8a2dbf142dfcc7ab, 0x6e3569326c784338}, - {0xacb92ed9397bf996, 0x49c2c37f07965405}, - {0xd7e77a8f87daf7fb, 0xdc33745ec97be907}, - {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a4}, - {0xa8acd7c0222311bc, 0xc40832ea0d68ce0d}, - {0xd2d80db02aabd62b, 0xf50a3fa490c30191}, - {0x83c7088e1aab65db, 0x792667c6da79e0fb}, - {0xa4b8cab1a1563f52, 0x577001b891185939}, - {0xcde6fd5e09abcf26, 0xed4c0226b55e6f87}, - {0x80b05e5ac60b6178, 0x544f8158315b05b5}, - {0xa0dc75f1778e39d6, 0x696361ae3db1c722}, - {0xc913936dd571c84c, 0x03bc3a19cd1e38ea}, - {0xfb5878494ace3a5f, 0x04ab48a04065c724}, - {0x9d174b2dcec0e47b, 0x62eb0d64283f9c77}, - {0xc45d1df942711d9a, 0x3ba5d0bd324f8395}, - {0xf5746577930d6500, 0xca8f44ec7ee3647a}, - {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecc}, - {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67f}, - {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101f}, - {0x95d04aee3b80ece5, 0xbba1f1d158724a13}, - {0xbb445da9ca61281f, 0x2a8a6e45ae8edc98}, - {0xea1575143cf97226, 0xf52d09d71a3293be}, - {0x924d692ca61be758, 0x593c2626705f9c57}, - {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836d}, - {0xe498f455c38b997a, 0x0b6dfb9c0f956448}, - {0x8edf98b59a373fec, 0x4724bd4189bd5ead}, - {0xb2977ee300c50fe7, 0x58edec91ec2cb658}, - {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ee}, - {0x8b865b215899f46c, 0xbd79e0d20082ee75}, - {0xae67f1e9aec07187, 0xecd8590680a3aa12}, - {0xda01ee641a708de9, 0xe80e6f4820cc9496}, - {0x884134fe908658b2, 0x3109058d147fdcde}, - {0xaa51823e34a7eede, 0xbd4b46f0599fd416}, - {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91b}, - {0x850fadc09923329e, 0x03e2cf6bc604ddb1}, - {0xa6539930bf6bff45, 0x84db8346b786151d}, - {0xcfe87f7cef46ff16, 0xe612641865679a64}, - {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07f}, - {0xa26da3999aef7749, 0xe3be5e330f38f09e}, - {0xcb090c8001ab551c, 0x5cadf5bfd3072cc6}, - {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f7}, - {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afb}, - {0xc646d63501a1511d, 0xb281e1fd541501b9}, - {0xf7d88bc24209a565, 0x1f225a7ca91a4227}, - {0x9ae757596946075f, 0x3375788de9b06959}, - {0xc1a12d2fc3978937, 0x0052d6b1641c83af}, - {0xf209787bb47d6b84, 0xc0678c5dbd23a49b}, - {0x9745eb4d50ce6332, 0xf840b7ba963646e1}, - {0xbd176620a501fbff, 0xb650e5a93bc3d899}, - {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebf}, - {0x93ba47c980e98cdf, 0xc66f336c36b10138}, - {0xb8a8d9bbe123f017, 0xb80b0047445d4185}, - {0xe6d3102ad96cec1d, 0xa60dc059157491e6}, - {0x9043ea1ac7e41392, 0x87c89837ad68db30}, - {0xb454e4a179dd1877, 0x29babe4598c311fc}, - {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67b}, - {0x8ce2529e2734bb1d, 0x1899e4a65f58660d}, - {0xb01ae745b101e9e4, 0x5ec05dcff72e7f90}, - {0xdc21a1171d42645d, 0x76707543f4fa1f74}, - {0x899504ae72497eba, 0x6a06494a791c53a9}, - {0xabfa45da0edbde69, 0x0487db9d17636893}, - {0xd6f8d7509292d603, 0x45a9d2845d3c42b7}, - {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b3}, - {0xa7f26836f282b732, 0x8e6cac7768d7141f}, - {0xd1ef0244af2364ff, 0x3207d795430cd927}, - {0x8335616aed761f1f, 0x7f44e6bd49e807b9}, - {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a7}, - {0xcd036837130890a1, 0x36dba887c37a8c10}, - {0x802221226be55a64, 0xc2494954da2c978a}, - {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6d}, - {0xc83553c5c8965d3d, 0x6f92829494e5acc8}, - {0xfa42a8b73abbf48c, 0xcb772339ba1f17fa}, - {0x9c69a97284b578d7, 0xff2a760414536efc}, - {0xc38413cf25e2d70d, 0xfef5138519684abb}, - {0xf46518c2ef5b8cd1, 0x7eb258665fc25d6a}, - {0x98bf2f79d5993802, 0xef2f773ffbd97a62}, - {0xbeeefb584aff8603, 0xaafb550ffacfd8fb}, - {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf39}, - {0x952ab45cfa97a0b2, 0xdd945a747bf26184}, - {0xba756174393d88df, 0x94f971119aeef9e5}, - {0xe912b9d1478ceb17, 0x7a37cd5601aab85e}, - {0x91abb422ccb812ee, 0xac62e055c10ab33b}, - {0xb616a12b7fe617aa, 0x577b986b314d600a}, - {0xe39c49765fdf9d94, 0xed5a7e85fda0b80c}, - {0x8e41ade9fbebc27d, 0x14588f13be847308}, - {0xb1d219647ae6b31c, 0x596eb2d8ae258fc9}, - {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bc}, - {0x8aec23d680043bee, 0x25de7bb9480d5855}, - {0xada72ccc20054ae9, 0xaf561aa79a10ae6b}, - {0xd910f7ff28069da4, 0x1b2ba1518094da05}, - {0x87aa9aff79042286, 0x90fb44d2f05d0843}, - {0xa99541bf57452b28, 0x353a1607ac744a54}, - {0xd3fa922f2d1675f2, 0x42889b8997915ce9}, - {0x847c9b5d7c2e09b7, 0x69956135febada12}, - {0xa59bc234db398c25, 0x43fab9837e699096}, - {0xcf02b2c21207ef2e, 0x94f967e45e03f4bc}, - {0x8161afb94b44f57d, 0x1d1be0eebac278f6}, - {0xa1ba1ba79e1632dc, 0x6462d92a69731733}, - {0xca28a291859bbf93, 0x7d7b8f7503cfdcff}, - {0xfcb2cb35e702af78, 0x5cda735244c3d43f}, - {0x9defbf01b061adab, 0x3a0888136afa64a8}, - {0xc56baec21c7a1916, 0x088aaa1845b8fdd1}, - {0xf6c69a72a3989f5b, 0x8aad549e57273d46}, - {0x9a3c2087a63f6399, 0x36ac54e2f678864c}, - {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7de}, - {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d6}, - {0x969eb7c47859e743, 0x9f644ae5a4b1b326}, - {0xbc4665b596706114, 0x873d5d9f0dde1fef}, - {0xeb57ff22fc0c7959, 0xa90cb506d155a7eb}, - {0x9316ff75dd87cbd8, 0x09a7f12442d588f3}, - {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb30}, - {0xe5d3ef282a242e81, 0x8f1668c8a86da5fb}, - {0x8fa475791a569d10, 0xf96e017d694487bd}, - {0xb38d92d760ec4455, 0x37c981dcc395a9ad}, - {0xe070f78d3927556a, 0x85bbe253f47b1418}, - {0x8c469ab843b89562, 0x93956d7478ccec8f}, - {0xaf58416654a6babb, 0x387ac8d1970027b3}, - {0xdb2e51bfe9d0696a, 0x06997b05fcc0319f}, - {0x88fcf317f22241e2, 0x441fece3bdf81f04}, - {0xab3c2fddeeaad25a, 0xd527e81cad7626c4}, - {0xd60b3bd56a5586f1, 0x8a71e223d8d3b075}, - {0x85c7056562757456, 0xf6872d5667844e4a}, - {0xa738c6bebb12d16c, 0xb428f8ac016561dc}, - {0xd106f86e69d785c7, 0xe13336d701beba53}, - {0x82a45b450226b39c, 0xecc0024661173474}, - {0xa34d721642b06084, 0x27f002d7f95d0191}, - {0xcc20ce9bd35c78a5, 0x31ec038df7b441f5}, - {0xff290242c83396ce, 0x7e67047175a15272}, - {0x9f79a169bd203e41, 0x0f0062c6e984d387}, - {0xc75809c42c684dd1, 0x52c07b78a3e60869}, - {0xf92e0c3537826145, 0xa7709a56ccdf8a83}, - {0x9bbcc7a142b17ccb, 0x88a66076400bb692}, - {0xc2abf989935ddbfe, 0x6acff893d00ea436}, - {0xf356f7ebf83552fe, 0x0583f6b8c4124d44}, - {0x98165af37b2153de, 0xc3727a337a8b704b}, - {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5d}, - {0xeda2ee1c7064130c, 0x1162def06f79df74}, - {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba9}, - {0xb9a74a0637ce2ee1, 0x6d953e2bd7173693}, - {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0438}, - {0x910ab1d4db9914a0, 0x1d9c9892400a22a3}, - {0xb54d5e4a127f59c8, 0x2503beb6d00cab4c}, - {0xe2a0b5dc971f303a, 0x2e44ae64840fd61e}, - {0x8da471a9de737e24, 0x5ceaecfed289e5d3}, - {0xb10d8e1456105dad, 0x7425a83e872c5f48}, - {0xdd50f1996b947518, 0xd12f124e28f7771a}, - {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa70}, - {0xace73cbfdc0bfb7b, 0x636cc64d1001550c}, - {0xd8210befd30efa5a, 0x3c47f7e05401aa4f}, - {0x8714a775e3e95c78, 0x65acfaec34810a72}, - {0xa8d9d1535ce3b396, 0x7f1839a741a14d0e}, - {0xd31045a8341ca07c, 0x1ede48111209a051}, - {0x83ea2b892091e44d, 0x934aed0aab460433}, - {0xa4e4b66b68b65d60, 0xf81da84d56178540}, - {0xce1de40642e3f4b9, 0x36251260ab9d668f}, - {0x80d2ae83e9ce78f3, 0xc1d72b7c6b42601a}, - {0xa1075a24e4421730, 0xb24cf65b8612f820}, - {0xc94930ae1d529cfc, 0xdee033f26797b628}, - {0xfb9b7cd9a4a7443c, 0x169840ef017da3b2}, - {0x9d412e0806e88aa5, 0x8e1f289560ee864f}, - {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e3}, - {0xf5b5d7ec8acb58a2, 0xae10af696774b1dc}, - {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef2a}, - {0xbff610b0cc6edd3f, 0x17fd090a58d32af4}, - {0xeff394dcff8a948e, 0xddfc4b4cef07f5b1}, - {0x95f83d0a1fb69cd9, 0x4abdaf101564f98f}, - {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f2}, - {0xea53df5fd18d5513, 0x84c86189216dc5ee}, - {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb5}, - {0xb7118682dbb66a77, 0x3fbc8c33221dc2a2}, - {0xe4d5e82392a40515, 0x0fabaf3feaa5334b}, - {0x8f05b1163ba6832d, 0x29cb4d87f2a7400f}, - {0xb2c71d5bca9023f8, 0x743e20e9ef511013}, - {0xdf78e4b2bd342cf6, 0x914da9246b255417}, - {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548f}, - {0xae9672aba3d0c320, 0xa184ac2473b529b2}, - {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741f}, - {0x8865899617fb1871, 0x7e2fa67c7a658893}, - {0xaa7eebfb9df9de8d, 0xddbb901b98feeab8}, - {0xd51ea6fa85785631, 0x552a74227f3ea566}, - {0x8533285c936b35de, 0xd53a88958f872760}, - {0xa67ff273b8460356, 0x8a892abaf368f138}, - {0xd01fef10a657842c, 0x2d2b7569b0432d86}, - {0x8213f56a67f6b29b, 0x9c3b29620e29fc74}, - {0xa298f2c501f45f42, 0x8349f3ba91b47b90}, - {0xcb3f2f7642717713, 0x241c70a936219a74}, - {0xfe0efb53d30dd4d7, 0xed238cd383aa0111}, - {0x9ec95d1463e8a506, 0xf4363804324a40ab}, - {0xc67bb4597ce2ce48, 0xb143c6053edcd0d6}, - {0xf81aa16fdc1b81da, 0xdd94b7868e94050b}, - {0x9b10a4e5e9913128, 0xca7cf2b4191c8327}, - {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f1}, - {0xf24a01a73cf2dccf, 0xbc633b39673c8ced}, - {0x976e41088617ca01, 0xd5be0503e085d814}, - {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e19}, - {0xec9c459d51852ba2, 0xddf8e7d60ed1219f}, - {0x93e1ab8252f33b45, 0xcabb90e5c942b504}, - {0xb8da1662e7b00a17, 0x3d6a751f3b936244}, - {0xe7109bfba19c0c9d, 0x0cc512670a783ad5}, - {0x906a617d450187e2, 0x27fb2b80668b24c6}, - {0xb484f9dc9641e9da, 0xb1f9f660802dedf7}, - {0xe1a63853bbd26451, 0x5e7873f8a0396974}, - {0x8d07e33455637eb2, 0xdb0b487b6423e1e9}, - {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda63}, - {0xdc5c5301c56b75f7, 0x7641a140cc7810fc}, - {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9e}, - {0xac2820d9623bf429, 0x546345fa9fbdcd45}, - {0xd732290fbacaf133, 0xa97c177947ad4096}, - {0x867f59a9d4bed6c0, 0x49ed8eabcccc485e}, - {0xa81f301449ee8c70, 0x5c68f256bfff5a75}, - {0xd226fc195c6a2f8c, 0x73832eec6fff3112}, - {0x83585d8fd9c25db7, 0xc831fd53c5ff7eac}, - {0xa42e74f3d032f525, 0xba3e7ca8b77f5e56}, - {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35ec}, - {0x80444b5e7aa7cf85, 0x7980d163cf5b81b4}, - {0xa0555e361951c366, 0xd7e105bcc3326220}, - {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa8}, - {0xfa856334878fc150, 0xb14f98f6f0feb952}, - {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d4}, - {0xc3b8358109e84f07, 0x0a862f80ec4700c9}, - {0xf4a642e14c6262c8, 0xcd27bb612758c0fb}, - {0x98e7e9cccfbd7dbd, 0x8038d51cb897789d}, - {0xbf21e44003acdd2c, 0xe0470a63e6bd56c4}, - {0xeeea5d5004981478, 0x1858ccfce06cac75}, - {0x95527a5202df0ccb, 0x0f37801e0c43ebc9}, - {0xbaa718e68396cffd, 0xd30560258f54e6bb}, - {0xe950df20247c83fd, 0x47c6b82ef32a206a}, - {0x91d28b7416cdd27e, 0x4cdc331d57fa5442}, - {0xb6472e511c81471d, 0xe0133fe4adf8e953}, - {0xe3d8f9e563a198e5, 0x58180fddd97723a7}, - {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7649}, - {0xb201833b35d63f73, 0x2cd2cc6551e513db}, - {0xde81e40a034bcf4f, 0xf8077f7ea65e58d2}, - {0x8b112e86420f6191, 0xfb04afaf27faf783}, - {0xadd57a27d29339f6, 0x79c5db9af1f9b564}, - {0xd94ad8b1c7380874, 0x18375281ae7822bd}, - {0x87cec76f1c830548, 0x8f2293910d0b15b6}, - {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb23}, - {0xd433179d9c8cb841, 0x5fa60692a46151ec}, - {0x849feec281d7f328, 0xdbc7c41ba6bcd334}, - {0xa5c7ea73224deff3, 0x12b9b522906c0801}, - {0xcf39e50feae16bef, 0xd768226b34870a01}, - {0x81842f29f2cce375, 0xe6a1158300d46641}, - {0xa1e53af46f801c53, 0x60495ae3c1097fd1}, - {0xca5e89b18b602368, 0x385bb19cb14bdfc5}, - {0xfcf62c1dee382c42, 0x46729e03dd9ed7b6}, - {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d2}, - {0xc5a05277621be293, 0xc7098b7305241886}, - {0xf70867153aa2db38, 0xb8cbee4fc66d1ea8} + const __uint128_t p = static_cast<__uint128_t>(x) * y; + return {std::uint64_t(p >> 64), std::uint64_t(p)}; +#elif defined(_MSC_VER) && defined(_M_X64) + std::uint64_t hi; + std::uint64_t lo = _umul128(x, y, &hi); + return {hi, lo}; +#elif defined(_MSC_VER) && defined(_M_ARM64) + return {__umulh(x, y), x * y}; +#else + const std::uint64_t a = x >> 32; + const std::uint64_t b = std::uint32_t(x); + const std::uint64_t c = y >> 32; + const std::uint64_t d = std::uint32_t(y); + const std::uint64_t ac = a * c; + const std::uint64_t bc = b * c; + const std::uint64_t ad = a * d; + const std::uint64_t bd = b * d; + const std::uint64_t cs = (bd >> 32) + std::uint32_t(ad) + std::uint32_t(bc); + return {ac + (ad >> 32) + (bc >> 32) + (cs >> 32), + (cs << 32) + std::uint32_t(bd)}; +#endif +} + +simdjson_really_inline std::uint64_t umul128_hi64(std::uint64_t x, std::uint64_t y) noexcept { + return umul128(x, y).hi; +} + +// (x * y + c) >> 64 +simdjson_really_inline std::uint64_t umul128_add_hi64(std::uint64_t x, std::uint64_t y, + std::uint64_t c) noexcept { + const uint128 p = umul128(x, y); + return p.hi + (p.lo + c < p.lo ? 1 : 0); +} + +// Upper 128 bits of the 192-bit product (x_hi * 2^64 + x_lo) * y. +simdjson_really_inline uint128 umul192_hi128(std::uint64_t x_hi, std::uint64_t x_lo, + std::uint64_t y) noexcept { + const uint128 p = umul128(x_hi, y); + const std::uint64_t lo = p.lo + umul128_hi64(x_lo, y); + return {p.hi + (lo < p.lo ? 1 : 0), lo}; +} + +simdjson_really_inline int clz64(std::uint64_t x) noexcept { +#if defined(_MSC_VER) && !defined(__clang__) && (defined(_M_X64) || defined(_M_ARM64)) + unsigned long idx; + _BitScanReverse64(&idx, x); + return 63 - int(idx); +#elif defined(_MSC_VER) && !defined(__clang__) + unsigned long idx; + if (_BitScanReverse(&idx, std::uint32_t(x >> 32))) { + return 31 - int(idx); + } + _BitScanReverse(&idx, std::uint32_t(x)); + return 63 - int(idx); +#else + return __builtin_clzll(x); +#endif +} + +// floor(log10(2^bin_exp)) if regular, else floor(log10(3/4 * 2^bin_exp)). +simdjson_really_inline int compute_dec_exp(int bin_exp, bool regular) noexcept { + return (bin_exp * 315653 - (regular ? 0 : 131072)) >> 20; +} + +// Shift that puts the decimal point of bin_sig * 2^bin_exp / 10^dec_exp at a +// fixed bit position of the 128-bit product. +simdjson_really_inline int compute_exp_shift(int bin_exp, int dec_exp) noexcept { + const int pow10_bin_exp = (-dec_exp * 217707) >> 16; + return bin_exp + pow10_bin_exp + 1; +} + +constexpr int num_sig_bits = 52; +constexpr int exp_offset = 1023 + num_sig_bits; +constexpr std::uint64_t implicit_bit = std::uint64_t(1) << num_sig_bits; +constexpr int extra_shift = 9; +constexpr int pow10_min_k = -293; + +// 128-bit significands of 10^k rounded down, k in [-293, 323]. +static const uint128 pow10_significands[617] = { + {0xcc5fc196fefd7d0c, 0x1e53ed49a96272c8}, // -293 + {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7a}, // -292 + {0x9faacf3df73609b1, 0x77b191618c54e9ac}, // -291 + {0xc795830d75038c1d, 0xd59df5b9ef6a2417}, // -290 + {0xf97ae3d0d2446f25, 0x4b0573286b44ad1d}, // -289 + {0x9becce62836ac577, 0x4ee367f9430aec32}, // -288 + {0xc2e801fb244576d5, 0x229c41f793cda73f}, // -287 + {0xf3a20279ed56d48a, 0x6b43527578c1110f}, // -286 + {0x9845418c345644d6, 0x830a13896b78aaa9}, // -285 + {0xbe5691ef416bd60c, 0x23cc986bc656d553}, // -284 + {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa8}, // -283 + {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6a9}, // -282 + {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc53}, // -281 + {0xe858ad248f5c22c9, 0xd1b3400f8f9cff68}, // -280 + {0x91376c36d99995be, 0x23100809b9c21fa1}, // -279 + {0xb58547448ffffb2d, 0xabd40a0c2832a78a}, // -278 + {0xe2e69915b3fff9f9, 0x16c90c8f323f516c}, // -277 + {0x8dd01fad907ffc3b, 0xae3da7d97f6792e3}, // -276 + {0xb1442798f49ffb4a, 0x99cd11cfdf41779c}, // -275 + {0xdd95317f31c7fa1d, 0x40405643d711d583}, // -274 + {0x8a7d3eef7f1cfc52, 0x482835ea666b2572}, // -273 + {0xad1c8eab5ee43b66, 0xda3243650005eecf}, // -272 + {0xd863b256369d4a40, 0x90bed43e40076a82}, // -271 + {0x873e4f75e2224e68, 0x5a7744a6e804a291}, // -270 + {0xa90de3535aaae202, 0x711515d0a205cb36}, // -269 + {0xd3515c2831559a83, 0x0d5a5b44ca873e03}, // -268 + {0x8412d9991ed58091, 0xe858790afe9486c2}, // -267 + {0xa5178fff668ae0b6, 0x626e974dbe39a872}, // -266 + {0xce5d73ff402d98e3, 0xfb0a3d212dc8128f}, // -265 + {0x80fa687f881c7f8e, 0x7ce66634bc9d0b99}, // -264 + {0xa139029f6a239f72, 0x1c1fffc1ebc44e80}, // -263 + {0xc987434744ac874e, 0xa327ffb266b56220}, // -262 + {0xfbe9141915d7a922, 0x4bf1ff9f0062baa8}, // -261 + {0x9d71ac8fada6c9b5, 0x6f773fc3603db4a9}, // -260 + {0xc4ce17b399107c22, 0xcb550fb4384d21d3}, // -259 + {0xf6019da07f549b2b, 0x7e2a53a146606a48}, // -258 + {0x99c102844f94e0fb, 0x2eda7444cbfc426d}, // -257 + {0xc0314325637a1939, 0xfa911155fefb5308}, // -256 + {0xf03d93eebc589f88, 0x793555ab7eba27ca}, // -255 + {0x96267c7535b763b5, 0x4bc1558b2f3458de}, // -254 + {0xbbb01b9283253ca2, 0x9eb1aaedfb016f16}, // -253 + {0xea9c227723ee8bcb, 0x465e15a979c1cadc}, // -252 + {0x92a1958a7675175f, 0x0bfacd89ec191ec9}, // -251 + {0xb749faed14125d36, 0xcef980ec671f667b}, // -250 + {0xe51c79a85916f484, 0x82b7e12780e7401a}, // -249 + {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908810}, // -248 + {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa15}, // -247 + {0xdfbdcece67006ac9, 0x67a791e093e1d49a}, // -246 + {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e0}, // -245 + {0xaecc49914078536d, 0x58fae9f773886e18}, // -244 + {0xda7f5bf590966848, 0xaf39a475506a899e}, // -243 + {0x888f99797a5e012d, 0x6d8406c952429603}, // -242 + {0xaab37fd7d8f58178, 0xc8e5087ba6d33b83}, // -241 + {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a64}, // -240 + {0x855c3be0a17fcd26, 0x5cf2eea09a55067f}, // -239 + {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481e}, // -238 + {0xd0601d8efc57b08b, 0xf13b94daf124da26}, // -237 + {0x823c12795db6ce57, 0x76c53d08d6b70858}, // -236 + {0xa2cb1717b52481ed, 0x54768c4b0c64ca6e}, // -235 + {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd09}, // -234 + {0xfe5d54150b090b02, 0xd3f93b35435d7c4c}, // -233 + {0x9efa548d26e5a6e1, 0xc47bc5014a1a6daf}, // -232 + {0xc6b8e9b0709f109a, 0x359ab6419ca1091b}, // -231 + {0xf867241c8cc6d4c0, 0xc30163d203c94b62}, // -230 + {0x9b407691d7fc44f8, 0x79e0de63425dcf1d}, // -229 + {0xc21094364dfb5636, 0x985915fc12f542e4}, // -228 + {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939d}, // -227 + {0x979cf3ca6cec5b5a, 0xa705992ceecf9c42}, // -226 + {0xbd8430bd08277231, 0x50c6ff782a838353}, // -225 + {0xece53cec4a314ebd, 0xa4f8bf5635246428}, // -224 + {0x940f4613ae5ed136, 0x871b7795e136be99}, // -223 + {0xb913179899f68584, 0x28e2557b59846e3f}, // -222 + {0xe757dd7ec07426e5, 0x331aeada2fe589cf}, // -221 + {0x9096ea6f3848984f, 0x3ff0d2c85def7621}, // -220 + {0xb4bca50b065abe63, 0x0fed077a756b53a9}, // -219 + {0xe1ebce4dc7f16dfb, 0xd3e8495912c62894}, // -218 + {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95c}, // -217 + {0xb080392cc4349dec, 0xbd8d794d96aacfb3}, // -216 + {0xdca04777f541c567, 0xecf0d7a0fc5583a0}, // -215 + {0x89e42caaf9491b60, 0xf41686c49db57244}, // -214 + {0xac5d37d5b79b6239, 0x311c2875c522ced5}, // -213 + {0xd77485cb25823ac7, 0x7d633293366b828b}, // -212 + {0x86a8d39ef77164bc, 0xae5dff9c02033197}, // -211 + {0xa8530886b54dbdeb, 0xd9f57f830283fdfc}, // -210 + {0xd267caa862a12d66, 0xd072df63c324fd7b}, // -209 + {0x8380dea93da4bc60, 0x4247cb9e59f71e6d}, // -208 + {0xa46116538d0deb78, 0x52d9be85f074e608}, // -207 + {0xcd795be870516656, 0x67902e276c921f8b}, // -206 + {0x806bd9714632dff6, 0x00ba1cd8a3db53b6}, // -205 + {0xa086cfcd97bf97f3, 0x80e8a40eccd228a4}, // -204 + {0xc8a883c0fdaf7df0, 0x6122cd128006b2cd}, // -203 + {0xfad2a4b13d1b5d6c, 0x796b805720085f81}, // -202 + {0x9cc3a6eec6311a63, 0xcbe3303674053bb0}, // -201 + {0xc3f490aa77bd60fc, 0xbedbfc4411068a9c}, // -200 + {0xf4f1b4d515acb93b, 0xee92fb5515482d44}, // -199 + {0x991711052d8bf3c5, 0x751bdd152d4d1c4a}, // -198 + {0xbf5cd54678eef0b6, 0xd262d45a78a0635d}, // -197 + {0xef340a98172aace4, 0x86fb897116c87c34}, // -196 + {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da0}, // -195 + {0xbae0a846d2195712, 0x8974836059cca109}, // -194 + {0xe998d258869facd7, 0x2bd1a438703fc94b}, // -193 + {0x91ff83775423cc06, 0x7b6306a34627ddcf}, // -192 + {0xb67f6455292cbf08, 0x1a3bc84c17b1d542}, // -191 + {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a93}, // -190 + {0x8e938662882af53e, 0x547eb47b7282ee9c}, // -189 + {0xb23867fb2a35b28d, 0xe99e619a4f23aa43}, // -188 + {0xdec681f9f4c31f31, 0x6405fa00e2ec94d4}, // -187 + {0x8b3c113c38f9f37e, 0xde83bc408dd3dd04}, // -186 + {0xae0b158b4738705e, 0x9624ab50b148d445}, // -185 + {0xd98ddaee19068c76, 0x3badd624dd9b0957}, // -184 + {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d6}, // -183 + {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4c}, // -182 + {0xd47487cc8470652b, 0x7647c3200069671f}, // -181 + {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e073}, // -180 + {0xa5fb0a17c777cf09, 0xf468107100525890}, // -179 + {0xcf79cc9db955c2cc, 0x7182148d4066eeb4}, // -178 + {0x81ac1fe293d599bf, 0xc6f14cd848405530}, // -177 + {0xa21727db38cb002f, 0xb8ada00e5a506a7c}, // -176 + {0xca9cf1d206fdc03b, 0xa6d90811f0e4851c}, // -175 + {0xfd442e4688bd304a, 0x908f4a166d1da663}, // -174 + {0x9e4a9cec15763e2e, 0x9a598e4e043287fe}, // -173 + {0xc5dd44271ad3cdba, 0x40eff1e1853f29fd}, // -172 + {0xf7549530e188c128, 0xd12bee59e68ef47c}, // -171 + {0x9a94dd3e8cf578b9, 0x82bb74f8301958ce}, // -170 + {0xc13a148e3032d6e7, 0xe36a52363c1faf01}, // -169 + {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac1}, // -168 + {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0b9}, // -167 + {0xbcb2b812db11a5de, 0x7415d448f6b6f0e7}, // -166 + {0xebdf661791d60f56, 0x111b495b3464ad21}, // -165 + {0x936b9fcebb25c995, 0xcab10dd900beec34}, // -164 + {0xb84687c269ef3bfb, 0x3d5d514f40eea742}, // -163 + {0xe65829b3046b0afa, 0x0cb4a5a3112a5112}, // -162 + {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ab}, // -161 + {0xb3f4e093db73a093, 0x59ed216765690f56}, // -160 + {0xe0f218b8d25088b8, 0x306869c13ec3532c}, // -159 + {0x8c974f7383725573, 0x1e414218c73a13fb}, // -158 + {0xafbd2350644eeacf, 0xe5d1929ef90898fa}, // -157 + {0xdbac6c247d62a583, 0xdf45f746b74abf39}, // -156 + {0x894bc396ce5da772, 0x6b8bba8c328eb783}, // -155 + {0xab9eb47c81f5114f, 0x066ea92f3f326564}, // -154 + {0xd686619ba27255a2, 0xc80a537b0efefebd}, // -153 + {0x8613fd0145877585, 0xbd06742ce95f5f36}, // -152 + {0xa798fc4196e952e7, 0x2c48113823b73704}, // -151 + {0xd17f3b51fca3a7a0, 0xf75a15862ca504c5}, // -150 + {0x82ef85133de648c4, 0x9a984d73dbe722fb}, // -149 + {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebba}, // -148 + {0xcc963fee10b7d1b3, 0x318df905079926a8}, // -147 + {0xffbbcfe994e5c61f, 0xfdf17746497f7052}, // -146 + {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa633}, // -145 + {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc0}, // -144 + {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b0}, // -143 + {0x9c1661a651213e2d, 0x06bea10ca65c084e}, // -142 + {0xc31bfa0fe5698db8, 0x486e494fcff30a62}, // -141 + {0xf3e2f893dec3f126, 0x5a89dba3c3efccfa}, // -140 + {0x986ddb5c6b3a76b7, 0xf89629465a75e01c}, // -139 + {0xbe89523386091465, 0xf6bbb397f1135823}, // -138 + {0xee2ba6c0678b597f, 0x746aa07ded582e2c}, // -137 + {0x94db483840b717ef, 0xa8c2a44eb4571cdc}, // -136 + {0xba121a4650e4ddeb, 0x92f34d62616ce413}, // -135 + {0xe896a0d7e51e1566, 0x77b020baf9c81d17}, // -134 + {0x915e2486ef32cd60, 0x0ace1474dc1d122e}, // -133 + {0xb5b5ada8aaff80b8, 0x0d819992132456ba}, // -132 + {0xe3231912d5bf60e6, 0x10e1fff697ed6c69}, // -131 + {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c1}, // -130 + {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb2}, // -129 + {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbde}, // -128 + {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96b}, // -127 + {0xad4ab7112eb3929d, 0x86c16c98d2c953c6}, // -126 + {0xd89d64d57a607744, 0xe871c7bf077ba8b7}, // -125 + {0x87625f056c7c4a8b, 0x11471cd764ad4972}, // -124 + {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bcf}, // -123 + {0xd389b47879823479, 0x4aff1d108d4ec2c3}, // -122 + {0x843610cb4bf160cb, 0xcedf722a585139ba}, // -121 + {0xa54394fe1eedb8fe, 0xc2974eb4ee658828}, // -120 + {0xce947a3da6a9273e, 0x733d226229feea32}, // -119 + {0x811ccc668829b887, 0x0806357d5a3f525f}, // -118 + {0xa163ff802a3426a8, 0xca07c2dcb0cf26f7}, // -117 + {0xc9bcff6034c13052, 0xfc89b393dd02f0b5}, // -116 + {0xfc2c3f3841f17c67, 0xbbac2078d443ace2}, // -115 + {0x9d9ba7832936edc0, 0xd54b944b84aa4c0d}, // -114 + {0xc5029163f384a931, 0x0a9e795e65d4df11}, // -113 + {0xf64335bcf065d37d, 0x4d4617b5ff4a16d5}, // -112 + {0x99ea0196163fa42e, 0x504bced1bf8e4e45}, // -111 + {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d6}, // -110 + {0xf07da27a82c37088, 0x5d767327bb4e5a4c}, // -109 + {0x964e858c91ba2655, 0x3a6a07f8d510f86f}, // -108 + {0xbbe226efb628afea, 0x890489f70a55368b}, // -107 + {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842e}, // -106 + {0x92c8ae6b464fc96f, 0x3b0b8bc90012929d}, // -105 + {0xb77ada0617e3bbcb, 0x09ce6ebb40173744}, // -104 + {0xe55990879ddcaabd, 0xcc420a6a101d0515}, // -103 + {0x8f57fa54c2a9eab6, 0x9fa946824a12232d}, // -102 + {0xb32df8e9f3546564, 0x47939822dc96abf9}, // -101 + {0xdff9772470297ebd, 0x59787e2b93bc56f7}, // -100 + {0x8bfbea76c619ef36, 0x57eb4edb3c55b65a}, // -99 + {0xaefae51477a06b03, 0xede622920b6b23f1}, // -98 + {0xdab99e59958885c4, 0xe95fab368e45eced}, // -97 + {0x88b402f7fd75539b, 0x11dbcb0218ebb414}, // -96 + {0xaae103b5fcd2a881, 0xd652bdc29f26a119}, // -95 + {0xd59944a37c0752a2, 0x4be76d3346f0495f}, // -94 + {0x857fcae62d8493a5, 0x6f70a4400c562ddb}, // -93 + {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb952}, // -92 + {0xd097ad07a71f26b2, 0x7e2000a41346a7a7}, // -91 + {0x825ecc24c873782f, 0x8ed400668c0c28c8}, // -90 + {0xa2f67f2dfa90563b, 0x728900802f0f32fa}, // -89 + {0xcbb41ef979346bca, 0x4f2b40a03ad2ffb9}, // -88 + {0xfea126b7d78186bc, 0xe2f610c84987bfa8}, // -87 + {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7c9}, // -86 + {0xc6ede63fa05d3143, 0x91503d1c79720dbb}, // -85 + {0xf8a95fcf88747d94, 0x75a44c6397ce912a}, // -84 + {0x9b69dbe1b548ce7c, 0xc986afbe3ee11aba}, // -83 + {0xc24452da229b021b, 0xfbe85badce996168}, // -82 + {0xf2d56790ab41c2a2, 0xfae27299423fb9c3}, // -81 + {0x97c560ba6b0919a5, 0xdccd879fc967d41a}, // -80 + {0xbdb6b8e905cb600f, 0x5400e987bbc1c920}, // -79 + {0xed246723473e3813, 0x290123e9aab23b68}, // -78 + {0x9436c0760c86e30b, 0xf9a0b6720aaf6521}, // -77 + {0xb94470938fa89bce, 0xf808e40e8d5b3e69}, // -76 + {0xe7958cb87392c2c2, 0xb60b1d1230b20e04}, // -75 + {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c2}, // -74 + {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af3}, // -73 + {0xe2280b6c20dd5232, 0x25c6da63c38de1b0}, // -72 + {0x8d590723948a535f, 0x579c487e5a38ad0e}, // -71 + {0xb0af48ec79ace837, 0x2d835a9df0c6d851}, // -70 + {0xdcdb1b2798182244, 0xf8e431456cf88e65}, // -69 + {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b58ff}, // -68 + {0xac8b2d36eed2dac5, 0xe272467e3d222f3f}, // -67 + {0xd7adf884aa879177, 0x5b0ed81dcc6abb0f}, // -66 + {0x86ccbb52ea94baea, 0x98e947129fc2b4e9}, // -65 + {0xa87fea27a539e9a5, 0x3f2398d747b36224}, // -64 + {0xd29fe4b18e88640e, 0x8eec7f0d19a03aad}, // -63 + {0x83a3eeeef9153e89, 0x1953cf68300424ac}, // -62 + {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd7}, // -61 + {0xcdb02555653131b6, 0x3792f412cb06794d}, // -60 + {0x808e17555f3ebf11, 0xe2bbd88bbee40bd0}, // -59 + {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec4}, // -58 + {0xc8de047564d20a8b, 0xf245825a5a445275}, // -57 + {0xfb158592be068d2e, 0xeed6e2f0f0d56712}, // -56 + {0x9ced737bb6c4183d, 0x55464dd69685606b}, // -55 + {0xc428d05aa4751e4c, 0xaa97e14c3c26b886}, // -54 + {0xf53304714d9265df, 0xd53dd99f4b3066a8}, // -53 + {0x993fe2c6d07b7fab, 0xe546a8038efe4029}, // -52 + {0xbf8fdb78849a5f96, 0xde98520472bdd033}, // -51 + {0xef73d256a5c0f77c, 0x963e66858f6d4440}, // -50 + {0x95a8637627989aad, 0xdde7001379a44aa8}, // -49 + {0xbb127c53b17ec159, 0x5560c018580d5d52}, // -48 + {0xe9d71b689dde71af, 0xaab8f01e6e10b4a6}, // -47 + {0x9226712162ab070d, 0xcab3961304ca70e8}, // -46 + {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d22}, // -45 + {0xe45c10c42a2b3b05, 0x8cb89a7db77c506a}, // -44 + {0x8eb98a7a9a5b04e3, 0x77f3608e92adb242}, // -43 + {0xb267ed1940f1c61c, 0x55f038b237591ed3}, // -42 + {0xdf01e85f912e37a3, 0x6b6c46dec52f6688}, // -41 + {0x8b61313bbabce2c6, 0x2323ac4b3b3da015}, // -40 + {0xae397d8aa96c1b77, 0xabec975e0a0d081a}, // -39 + {0xd9c7dced53c72255, 0x96e7bd358c904a21}, // -38 + {0x881cea14545c7575, 0x7e50d64177da2e54}, // -37 + {0xaa242499697392d2, 0xdde50bd1d5d0b9e9}, // -36 + {0xd4ad2dbfc3d07787, 0x955e4ec64b44e864}, // -35 + {0x84ec3c97da624ab4, 0xbd5af13bef0b113e}, // -34 + {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58e}, // -33 + {0xcfb11ead453994ba, 0x67de18eda5814af2}, // -32 + {0x81ceb32c4b43fcf4, 0x80eacf948770ced7}, // -31 + {0xa2425ff75e14fc31, 0xa1258379a94d028d}, // -30 + {0xcad2f7f5359a3b3e, 0x096ee45813a04330}, // -29 + {0xfd87b5f28300ca0d, 0x8bca9d6e188853fc}, // -28 + {0x9e74d1b791e07e48, 0x775ea264cf55347d}, // -27 + {0xc612062576589dda, 0x95364afe032a819d}, // -26 + {0xf79687aed3eec551, 0x3a83ddbd83f52204}, // -25 + {0x9abe14cd44753b52, 0xc4926a9672793542}, // -24 + {0xc16d9a0095928a27, 0x75b7053c0f178293}, // -23 + {0xf1c90080baf72cb1, 0x5324c68b12dd6338}, // -22 + {0x971da05074da7bee, 0xd3f6fc16ebca5e03}, // -21 + {0xbce5086492111aea, 0x88f4bb1ca6bcf584}, // -20 + {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e5}, // -19 + {0x9392ee8e921d5d07, 0x3aff322e62439fcf}, // -18 + {0xb877aa3236a4b449, 0x09befeb9fad487c2}, // -17 + {0xe69594bec44de15b, 0x4c2ebe687989a9b3}, // -16 + {0x901d7cf73ab0acd9, 0x0f9d37014bf60a10}, // -15 + {0xb424dc35095cd80f, 0x538484c19ef38c94}, // -14 + {0xe12e13424bb40e13, 0x2865a5f206b06fb9}, // -13 + {0x8cbccc096f5088cb, 0xf93f87b7442e45d3}, // -12 + {0xafebff0bcb24aafe, 0xf78f69a51539d748}, // -11 + {0xdbe6fecebdedd5be, 0xb573440e5a884d1b}, // -10 + {0x89705f4136b4a597, 0x31680a88f8953030}, // -9 + {0xabcc77118461cefc, 0xfdc20d2b36ba7c3d}, // -8 + {0xd6bf94d5e57a42bc, 0x3d32907604691b4c}, // -7 + {0x8637bd05af6c69b5, 0xa63f9a49c2c1b10f}, // -6 + {0xa7c5ac471b478423, 0x0fcf80dc33721d53}, // -5 + {0xd1b71758e219652b, 0xd3c36113404ea4a8}, // -4 + {0x83126e978d4fdf3b, 0x645a1cac083126e9}, // -3 + {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a3}, // -2 + {0xcccccccccccccccc, 0xcccccccccccccccc}, // -1 + {0x8000000000000000, 0x0000000000000000}, // 0 + {0xa000000000000000, 0x0000000000000000}, // 1 + {0xc800000000000000, 0x0000000000000000}, // 2 + {0xfa00000000000000, 0x0000000000000000}, // 3 + {0x9c40000000000000, 0x0000000000000000}, // 4 + {0xc350000000000000, 0x0000000000000000}, // 5 + {0xf424000000000000, 0x0000000000000000}, // 6 + {0x9896800000000000, 0x0000000000000000}, // 7 + {0xbebc200000000000, 0x0000000000000000}, // 8 + {0xee6b280000000000, 0x0000000000000000}, // 9 + {0x9502f90000000000, 0x0000000000000000}, // 10 + {0xba43b74000000000, 0x0000000000000000}, // 11 + {0xe8d4a51000000000, 0x0000000000000000}, // 12 + {0x9184e72a00000000, 0x0000000000000000}, // 13 + {0xb5e620f480000000, 0x0000000000000000}, // 14 + {0xe35fa931a0000000, 0x0000000000000000}, // 15 + {0x8e1bc9bf04000000, 0x0000000000000000}, // 16 + {0xb1a2bc2ec5000000, 0x0000000000000000}, // 17 + {0xde0b6b3a76400000, 0x0000000000000000}, // 18 + {0x8ac7230489e80000, 0x0000000000000000}, // 19 + {0xad78ebc5ac620000, 0x0000000000000000}, // 20 + {0xd8d726b7177a8000, 0x0000000000000000}, // 21 + {0x878678326eac9000, 0x0000000000000000}, // 22 + {0xa968163f0a57b400, 0x0000000000000000}, // 23 + {0xd3c21bcecceda100, 0x0000000000000000}, // 24 + {0x84595161401484a0, 0x0000000000000000}, // 25 + {0xa56fa5b99019a5c8, 0x0000000000000000}, // 26 + {0xcecb8f27f4200f3a, 0x0000000000000000}, // 27 + {0x813f3978f8940984, 0x4000000000000000}, // 28 + {0xa18f07d736b90be5, 0x5000000000000000}, // 29 + {0xc9f2c9cd04674ede, 0xa400000000000000}, // 30 + {0xfc6f7c4045812296, 0x4d00000000000000}, // 31 + {0x9dc5ada82b70b59d, 0xf020000000000000}, // 32 + {0xc5371912364ce305, 0x6c28000000000000}, // 33 + {0xf684df56c3e01bc6, 0xc732000000000000}, // 34 + {0x9a130b963a6c115c, 0x3c7f400000000000}, // 35 + {0xc097ce7bc90715b3, 0x4b9f100000000000}, // 36 + {0xf0bdc21abb48db20, 0x1e86d40000000000}, // 37 + {0x96769950b50d88f4, 0x1314448000000000}, // 38 + {0xbc143fa4e250eb31, 0x17d955a000000000}, // 39 + {0xeb194f8e1ae525fd, 0x5dcfab0800000000}, // 40 + {0x92efd1b8d0cf37be, 0x5aa1cae500000000}, // 41 + {0xb7abc627050305ad, 0xf14a3d9e40000000}, // 42 + {0xe596b7b0c643c719, 0x6d9ccd05d0000000}, // 43 + {0x8f7e32ce7bea5c6f, 0xe4820023a2000000}, // 44 + {0xb35dbf821ae4f38b, 0xdda2802c8a800000}, // 45 + {0xe0352f62a19e306e, 0xd50b2037ad200000}, // 46 + {0x8c213d9da502de45, 0x4526f422cc340000}, // 47 + {0xaf298d050e4395d6, 0x9670b12b7f410000}, // 48 + {0xdaf3f04651d47b4c, 0x3c0cdd765f114000}, // 49 + {0x88d8762bf324cd0f, 0xa5880a69fb6ac800}, // 50 + {0xab0e93b6efee0053, 0x8eea0d047a457a00}, // 51 + {0xd5d238a4abe98068, 0x72a4904598d6d880}, // 52 + {0x85a36366eb71f041, 0x47a6da2b7f864750}, // 53 + {0xa70c3c40a64e6c51, 0x999090b65f67d924}, // 54 + {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d}, // 55 + {0x82818f1281ed449f, 0xbff8f10e7a8921a4}, // 56 + {0xa321f2d7226895c7, 0xaff72d52192b6a0d}, // 57 + {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764490}, // 58 + {0xfee50b7025c36a08, 0x02f236d04753d5b4}, // 59 + {0x9f4f2726179a2245, 0x01d762422c946590}, // 60 + {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef5}, // 61 + {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb2}, // 62 + {0x9b934c3b330c8577, 0x63cc55f49f88eb2f}, // 63 + {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fb}, // 64 + {0xf316271c7fc3908a, 0x8bef464e3945ef7a}, // 65 + {0x97edd871cfda3a56, 0x97758bf0e3cbb5ac}, // 66 + {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea317}, // 67 + {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bdd}, // 68 + {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6a}, // 69 + {0xb975d6b6ee39e436, 0xb3e2fd538e122b44}, // 70 + {0xe7d34c64a9c85d44, 0x60dbbca87196b616}, // 71 + {0x90e40fbeea1d3a4a, 0xbc8955e946fe31cd}, // 72 + {0xb51d13aea4a488dd, 0x6babab6398bdbe41}, // 73 + {0xe264589a4dcdab14, 0xc696963c7eed2dd1}, // 74 + {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca2}, // 75 + {0xb0de65388cc8ada8, 0x3b25a55f43294bcb}, // 76 + {0xdd15fe86affad912, 0x49ef0eb713f39ebe}, // 77 + {0x8a2dbf142dfcc7ab, 0x6e3569326c784337}, // 78 + {0xacb92ed9397bf996, 0x49c2c37f07965404}, // 79 + {0xd7e77a8f87daf7fb, 0xdc33745ec97be906}, // 80 + {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a3}, // 81 + {0xa8acd7c0222311bc, 0xc40832ea0d68ce0c}, // 82 + {0xd2d80db02aabd62b, 0xf50a3fa490c30190}, // 83 + {0x83c7088e1aab65db, 0x792667c6da79e0fa}, // 84 + {0xa4b8cab1a1563f52, 0x577001b891185938}, // 85 + {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86}, // 86 + {0x80b05e5ac60b6178, 0x544f8158315b05b4}, // 87 + {0xa0dc75f1778e39d6, 0x696361ae3db1c721}, // 88 + {0xc913936dd571c84c, 0x03bc3a19cd1e38e9}, // 89 + {0xfb5878494ace3a5f, 0x04ab48a04065c723}, // 90 + {0x9d174b2dcec0e47b, 0x62eb0d64283f9c76}, // 91 + {0xc45d1df942711d9a, 0x3ba5d0bd324f8394}, // 92 + {0xf5746577930d6500, 0xca8f44ec7ee36479}, // 93 + {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecb}, // 94 + {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67e}, // 95 + {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101e}, // 96 + {0x95d04aee3b80ece5, 0xbba1f1d158724a12}, // 97 + {0xbb445da9ca61281f, 0x2a8a6e45ae8edc97}, // 98 + {0xea1575143cf97226, 0xf52d09d71a3293bd}, // 99 + {0x924d692ca61be758, 0x593c2626705f9c56}, // 100 + {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836c}, // 101 + {0xe498f455c38b997a, 0x0b6dfb9c0f956447}, // 102 + {0x8edf98b59a373fec, 0x4724bd4189bd5eac}, // 103 + {0xb2977ee300c50fe7, 0x58edec91ec2cb657}, // 104 + {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ed}, // 105 + {0x8b865b215899f46c, 0xbd79e0d20082ee74}, // 106 + {0xae67f1e9aec07187, 0xecd8590680a3aa11}, // 107 + {0xda01ee641a708de9, 0xe80e6f4820cc9495}, // 108 + {0x884134fe908658b2, 0x3109058d147fdcdd}, // 109 + {0xaa51823e34a7eede, 0xbd4b46f0599fd415}, // 110 + {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91a}, // 111 + {0x850fadc09923329e, 0x03e2cf6bc604ddb0}, // 112 + {0xa6539930bf6bff45, 0x84db8346b786151c}, // 113 + {0xcfe87f7cef46ff16, 0xe612641865679a63}, // 114 + {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07e}, // 115 + {0xa26da3999aef7749, 0xe3be5e330f38f09d}, // 116 + {0xcb090c8001ab551c, 0x5cadf5bfd3072cc5}, // 117 + {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f6}, // 118 + {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afa}, // 119 + {0xc646d63501a1511d, 0xb281e1fd541501b8}, // 120 + {0xf7d88bc24209a565, 0x1f225a7ca91a4226}, // 121 + {0x9ae757596946075f, 0x3375788de9b06958}, // 122 + {0xc1a12d2fc3978937, 0x0052d6b1641c83ae}, // 123 + {0xf209787bb47d6b84, 0xc0678c5dbd23a49a}, // 124 + {0x9745eb4d50ce6332, 0xf840b7ba963646e0}, // 125 + {0xbd176620a501fbff, 0xb650e5a93bc3d898}, // 126 + {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebe}, // 127 + {0x93ba47c980e98cdf, 0xc66f336c36b10137}, // 128 + {0xb8a8d9bbe123f017, 0xb80b0047445d4184}, // 129 + {0xe6d3102ad96cec1d, 0xa60dc059157491e5}, // 130 + {0x9043ea1ac7e41392, 0x87c89837ad68db2f}, // 131 + {0xb454e4a179dd1877, 0x29babe4598c311fb}, // 132 + {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67a}, // 133 + {0x8ce2529e2734bb1d, 0x1899e4a65f58660c}, // 134 + {0xb01ae745b101e9e4, 0x5ec05dcff72e7f8f}, // 135 + {0xdc21a1171d42645d, 0x76707543f4fa1f73}, // 136 + {0x899504ae72497eba, 0x6a06494a791c53a8}, // 137 + {0xabfa45da0edbde69, 0x0487db9d17636892}, // 138 + {0xd6f8d7509292d603, 0x45a9d2845d3c42b6}, // 139 + {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2}, // 140 + {0xa7f26836f282b732, 0x8e6cac7768d7141e}, // 141 + {0xd1ef0244af2364ff, 0x3207d795430cd926}, // 142 + {0x8335616aed761f1f, 0x7f44e6bd49e807b8}, // 143 + {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a6}, // 144 + {0xcd036837130890a1, 0x36dba887c37a8c0f}, // 145 + {0x802221226be55a64, 0xc2494954da2c9789}, // 146 + {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6c}, // 147 + {0xc83553c5c8965d3d, 0x6f92829494e5acc7}, // 148 + {0xfa42a8b73abbf48c, 0xcb772339ba1f17f9}, // 149 + {0x9c69a97284b578d7, 0xff2a760414536efb}, // 150 + {0xc38413cf25e2d70d, 0xfef5138519684aba}, // 151 + {0xf46518c2ef5b8cd1, 0x7eb258665fc25d69}, // 152 + {0x98bf2f79d5993802, 0xef2f773ffbd97a61}, // 153 + {0xbeeefb584aff8603, 0xaafb550ffacfd8fa}, // 154 + {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf38}, // 155 + {0x952ab45cfa97a0b2, 0xdd945a747bf26183}, // 156 + {0xba756174393d88df, 0x94f971119aeef9e4}, // 157 + {0xe912b9d1478ceb17, 0x7a37cd5601aab85d}, // 158 + {0x91abb422ccb812ee, 0xac62e055c10ab33a}, // 159 + {0xb616a12b7fe617aa, 0x577b986b314d6009}, // 160 + {0xe39c49765fdf9d94, 0xed5a7e85fda0b80b}, // 161 + {0x8e41ade9fbebc27d, 0x14588f13be847307}, // 162 + {0xb1d219647ae6b31c, 0x596eb2d8ae258fc8}, // 163 + {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bb}, // 164 + {0x8aec23d680043bee, 0x25de7bb9480d5854}, // 165 + {0xada72ccc20054ae9, 0xaf561aa79a10ae6a}, // 166 + {0xd910f7ff28069da4, 0x1b2ba1518094da04}, // 167 + {0x87aa9aff79042286, 0x90fb44d2f05d0842}, // 168 + {0xa99541bf57452b28, 0x353a1607ac744a53}, // 169 + {0xd3fa922f2d1675f2, 0x42889b8997915ce8}, // 170 + {0x847c9b5d7c2e09b7, 0x69956135febada11}, // 171 + {0xa59bc234db398c25, 0x43fab9837e699095}, // 172 + {0xcf02b2c21207ef2e, 0x94f967e45e03f4bb}, // 173 + {0x8161afb94b44f57d, 0x1d1be0eebac278f5}, // 174 + {0xa1ba1ba79e1632dc, 0x6462d92a69731732}, // 175 + {0xca28a291859bbf93, 0x7d7b8f7503cfdcfe}, // 176 + {0xfcb2cb35e702af78, 0x5cda735244c3d43e}, // 177 + {0x9defbf01b061adab, 0x3a0888136afa64a7}, // 178 + {0xc56baec21c7a1916, 0x088aaa1845b8fdd0}, // 179 + {0xf6c69a72a3989f5b, 0x8aad549e57273d45}, // 180 + {0x9a3c2087a63f6399, 0x36ac54e2f678864b}, // 181 + {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7dd}, // 182 + {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d5}, // 183 + {0x969eb7c47859e743, 0x9f644ae5a4b1b325}, // 184 + {0xbc4665b596706114, 0x873d5d9f0dde1fee}, // 185 + {0xeb57ff22fc0c7959, 0xa90cb506d155a7ea}, // 186 + {0x9316ff75dd87cbd8, 0x09a7f12442d588f2}, // 187 + {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb2f}, // 188 + {0xe5d3ef282a242e81, 0x8f1668c8a86da5fa}, // 189 + {0x8fa475791a569d10, 0xf96e017d694487bc}, // 190 + {0xb38d92d760ec4455, 0x37c981dcc395a9ac}, // 191 + {0xe070f78d3927556a, 0x85bbe253f47b1417}, // 192 + {0x8c469ab843b89562, 0x93956d7478ccec8e}, // 193 + {0xaf58416654a6babb, 0x387ac8d1970027b2}, // 194 + {0xdb2e51bfe9d0696a, 0x06997b05fcc0319e}, // 195 + {0x88fcf317f22241e2, 0x441fece3bdf81f03}, // 196 + {0xab3c2fddeeaad25a, 0xd527e81cad7626c3}, // 197 + {0xd60b3bd56a5586f1, 0x8a71e223d8d3b074}, // 198 + {0x85c7056562757456, 0xf6872d5667844e49}, // 199 + {0xa738c6bebb12d16c, 0xb428f8ac016561db}, // 200 + {0xd106f86e69d785c7, 0xe13336d701beba52}, // 201 + {0x82a45b450226b39c, 0xecc0024661173473}, // 202 + {0xa34d721642b06084, 0x27f002d7f95d0190}, // 203 + {0xcc20ce9bd35c78a5, 0x31ec038df7b441f4}, // 204 + {0xff290242c83396ce, 0x7e67047175a15271}, // 205 + {0x9f79a169bd203e41, 0x0f0062c6e984d386}, // 206 + {0xc75809c42c684dd1, 0x52c07b78a3e60868}, // 207 + {0xf92e0c3537826145, 0xa7709a56ccdf8a82}, // 208 + {0x9bbcc7a142b17ccb, 0x88a66076400bb691}, // 209 + {0xc2abf989935ddbfe, 0x6acff893d00ea435}, // 210 + {0xf356f7ebf83552fe, 0x0583f6b8c4124d43}, // 211 + {0x98165af37b2153de, 0xc3727a337a8b704a}, // 212 + {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5c}, // 213 + {0xeda2ee1c7064130c, 0x1162def06f79df73}, // 214 + {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba8}, // 215 + {0xb9a74a0637ce2ee1, 0x6d953e2bd7173692}, // 216 + {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0437}, // 217 + {0x910ab1d4db9914a0, 0x1d9c9892400a22a2}, // 218 + {0xb54d5e4a127f59c8, 0x2503beb6d00cab4b}, // 219 + {0xe2a0b5dc971f303a, 0x2e44ae64840fd61d}, // 220 + {0x8da471a9de737e24, 0x5ceaecfed289e5d2}, // 221 + {0xb10d8e1456105dad, 0x7425a83e872c5f47}, // 222 + {0xdd50f1996b947518, 0xd12f124e28f77719}, // 223 + {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa6f}, // 224 + {0xace73cbfdc0bfb7b, 0x636cc64d1001550b}, // 225 + {0xd8210befd30efa5a, 0x3c47f7e05401aa4e}, // 226 + {0x8714a775e3e95c78, 0x65acfaec34810a71}, // 227 + {0xa8d9d1535ce3b396, 0x7f1839a741a14d0d}, // 228 + {0xd31045a8341ca07c, 0x1ede48111209a050}, // 229 + {0x83ea2b892091e44d, 0x934aed0aab460432}, // 230 + {0xa4e4b66b68b65d60, 0xf81da84d5617853f}, // 231 + {0xce1de40642e3f4b9, 0x36251260ab9d668e}, // 232 + {0x80d2ae83e9ce78f3, 0xc1d72b7c6b426019}, // 233 + {0xa1075a24e4421730, 0xb24cf65b8612f81f}, // 234 + {0xc94930ae1d529cfc, 0xdee033f26797b627}, // 235 + {0xfb9b7cd9a4a7443c, 0x169840ef017da3b1}, // 236 + {0x9d412e0806e88aa5, 0x8e1f289560ee864e}, // 237 + {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e2}, // 238 + {0xf5b5d7ec8acb58a2, 0xae10af696774b1db}, // 239 + {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef29}, // 240 + {0xbff610b0cc6edd3f, 0x17fd090a58d32af3}, // 241 + {0xeff394dcff8a948e, 0xddfc4b4cef07f5b0}, // 242 + {0x95f83d0a1fb69cd9, 0x4abdaf101564f98e}, // 243 + {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f1}, // 244 + {0xea53df5fd18d5513, 0x84c86189216dc5ed}, // 245 + {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb4}, // 246 + {0xb7118682dbb66a77, 0x3fbc8c33221dc2a1}, // 247 + {0xe4d5e82392a40515, 0x0fabaf3feaa5334a}, // 248 + {0x8f05b1163ba6832d, 0x29cb4d87f2a7400e}, // 249 + {0xb2c71d5bca9023f8, 0x743e20e9ef511012}, // 250 + {0xdf78e4b2bd342cf6, 0x914da9246b255416}, // 251 + {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548e}, // 252 + {0xae9672aba3d0c320, 0xa184ac2473b529b1}, // 253 + {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741e}, // 254 + {0x8865899617fb1871, 0x7e2fa67c7a658892}, // 255 + {0xaa7eebfb9df9de8d, 0xddbb901b98feeab7}, // 256 + {0xd51ea6fa85785631, 0x552a74227f3ea565}, // 257 + {0x8533285c936b35de, 0xd53a88958f87275f}, // 258 + {0xa67ff273b8460356, 0x8a892abaf368f137}, // 259 + {0xd01fef10a657842c, 0x2d2b7569b0432d85}, // 260 + {0x8213f56a67f6b29b, 0x9c3b29620e29fc73}, // 261 + {0xa298f2c501f45f42, 0x8349f3ba91b47b8f}, // 262 + {0xcb3f2f7642717713, 0x241c70a936219a73}, // 263 + {0xfe0efb53d30dd4d7, 0xed238cd383aa0110}, // 264 + {0x9ec95d1463e8a506, 0xf4363804324a40aa}, // 265 + {0xc67bb4597ce2ce48, 0xb143c6053edcd0d5}, // 266 + {0xf81aa16fdc1b81da, 0xdd94b7868e94050a}, // 267 + {0x9b10a4e5e9913128, 0xca7cf2b4191c8326}, // 268 + {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f0}, // 269 + {0xf24a01a73cf2dccf, 0xbc633b39673c8cec}, // 270 + {0x976e41088617ca01, 0xd5be0503e085d813}, // 271 + {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e18}, // 272 + {0xec9c459d51852ba2, 0xddf8e7d60ed1219e}, // 273 + {0x93e1ab8252f33b45, 0xcabb90e5c942b503}, // 274 + {0xb8da1662e7b00a17, 0x3d6a751f3b936243}, // 275 + {0xe7109bfba19c0c9d, 0x0cc512670a783ad4}, // 276 + {0x906a617d450187e2, 0x27fb2b80668b24c5}, // 277 + {0xb484f9dc9641e9da, 0xb1f9f660802dedf6}, // 278 + {0xe1a63853bbd26451, 0x5e7873f8a0396973}, // 279 + {0x8d07e33455637eb2, 0xdb0b487b6423e1e8}, // 280 + {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda62}, // 281 + {0xdc5c5301c56b75f7, 0x7641a140cc7810fb}, // 282 + {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9d}, // 283 + {0xac2820d9623bf429, 0x546345fa9fbdcd44}, // 284 + {0xd732290fbacaf133, 0xa97c177947ad4095}, // 285 + {0x867f59a9d4bed6c0, 0x49ed8eabcccc485d}, // 286 + {0xa81f301449ee8c70, 0x5c68f256bfff5a74}, // 287 + {0xd226fc195c6a2f8c, 0x73832eec6fff3111}, // 288 + {0x83585d8fd9c25db7, 0xc831fd53c5ff7eab}, // 289 + {0xa42e74f3d032f525, 0xba3e7ca8b77f5e55}, // 290 + {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35eb}, // 291 + {0x80444b5e7aa7cf85, 0x7980d163cf5b81b3}, // 292 + {0xa0555e361951c366, 0xd7e105bcc332621f}, // 293 + {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa7}, // 294 + {0xfa856334878fc150, 0xb14f98f6f0feb951}, // 295 + {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d3}, // 296 + {0xc3b8358109e84f07, 0x0a862f80ec4700c8}, // 297 + {0xf4a642e14c6262c8, 0xcd27bb612758c0fa}, // 298 + {0x98e7e9cccfbd7dbd, 0x8038d51cb897789c}, // 299 + {0xbf21e44003acdd2c, 0xe0470a63e6bd56c3}, // 300 + {0xeeea5d5004981478, 0x1858ccfce06cac74}, // 301 + {0x95527a5202df0ccb, 0x0f37801e0c43ebc8}, // 302 + {0xbaa718e68396cffd, 0xd30560258f54e6ba}, // 303 + {0xe950df20247c83fd, 0x47c6b82ef32a2069}, // 304 + {0x91d28b7416cdd27e, 0x4cdc331d57fa5441}, // 305 + {0xb6472e511c81471d, 0xe0133fe4adf8e952}, // 306 + {0xe3d8f9e563a198e5, 0x58180fddd97723a6}, // 307 + {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7648}, // 308 + {0xb201833b35d63f73, 0x2cd2cc6551e513da}, // 309 + {0xde81e40a034bcf4f, 0xf8077f7ea65e58d1}, // 310 + {0x8b112e86420f6191, 0xfb04afaf27faf782}, // 311 + {0xadd57a27d29339f6, 0x79c5db9af1f9b563}, // 312 + {0xd94ad8b1c7380874, 0x18375281ae7822bc}, // 313 + {0x87cec76f1c830548, 0x8f2293910d0b15b5}, // 314 + {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb22}, // 315 + {0xd433179d9c8cb841, 0x5fa60692a46151eb}, // 316 + {0x849feec281d7f328, 0xdbc7c41ba6bcd333}, // 317 + {0xa5c7ea73224deff3, 0x12b9b522906c0800}, // 318 + {0xcf39e50feae16bef, 0xd768226b34870a00}, // 319 + {0x81842f29f2cce375, 0xe6a1158300d46640}, // 320 + {0xa1e53af46f801c53, 0x60495ae3c1097fd0}, // 321 + {0xca5e89b18b602368, 0x385bb19cb14bdfc4}, // 322 + {0xfcf62c1dee382c42, 0x46729e03dd9ed7b5}, // 323 }; -// Per-format helper routines (binary64 specializations of the Dragonbox steps). -struct compute_mul_result { - std::uint64_t integer_part; - bool is_integer; +// The extra (17th) digit is (fractional + digit_offsets[fractional >> 60]) >> +// 60, which rounds to nearest with ties to even (see Zmij.lean upstream). +static const std::uint64_t digit_offsets[16] = { + 0x0333333333333333, 0, 0xf999999999999999, 0xf000000000000000, + 0xefffffffffffffff, 0xe666666666666667, 0xe000000000000000, + 0xdccccccccccccccd, 0xd333333333333333, 0xd000000000000000, + 0xc99999999999999a, 0xc000000000000000, 0xc000000000000000, + 0xb666666666666666, 0xb000000000000000, 0xaccccccccccccccc}; + +static const std::uint64_t pow10s[19] = { + 1ull, 10ull, 100ull, 1000ull, 10000ull, 100000ull, 1000000ull, + 10000000ull, 100000000ull, 1000000000ull, 10000000000ull, + 100000000000ull, 1000000000000ull, 10000000000000ull, + 100000000000000ull, 1000000000000000ull, 10000000000000000ull, + 100000000000000000ull, 1000000000000000000ull}; + +struct shortest_decimal { + std::uint64_t sig; // the shorter candidate, 15 or 16 digits for normals + int exp; + int last_digit; // 0 unless has_last_digit + bool has_last_digit; }; -struct compute_mul_parity_result { - bool parity; - bool is_integer; -}; - -inline compute_mul_result compute_mul(std::uint64_t u, uint128 c) noexcept { - const uint128 r = umul192_upper128(u, c); - return {r.high, r.low == 0}; -} - -inline std::uint64_t compute_delta(uint128 c, int beta) noexcept { - return c.high >> (total_bits - 1 - beta); -} - -inline compute_mul_parity_result compute_mul_parity(std::uint64_t two_f, - uint128 c, int beta) noexcept { - // beta is always in [1, 63] here. - const uint128 r = umul192_lower128(two_f, c); - return {((r.high >> (64 - beta)) & 1) != 0, - ((r.high << beta) | (r.low >> (64 - beta))) == 0}; -} -inline std::uint64_t -compute_left_endpoint_for_shorter_interval_case(uint128 c, int beta) noexcept { - return (c.high - (c.high >> (significand_bits + 2))) >> - (total_bits - significand_bits - 1 - beta); +// Shortest decimal for bin_sig * 2^(raw_exp - exp_offset). regular is false +// only for powers of two, whose lower neighbour is closer. +simdjson_really_inline shortest_decimal to_decimal(std::uint64_t bin_sig, int raw_exp, + bool regular) noexcept { + const int bin_exp = raw_exp - exp_offset; + if (simdjson_unlikely(!regular)) { + const int dec_exp = compute_dec_exp(bin_exp, false); + const int exp_shift = compute_exp_shift(bin_exp, dec_exp + 1); // [-3, 1] + const uint128 pow10 = pow10_significands[-dec_exp - 1 - pow10_min_k]; + // bin_sig is the implicit bit alone, so the product is a shift. + const int frac_shift = exp_shift + num_sig_bits; + const std::uint64_t fractional = + pow10.hi << frac_shift | pow10.lo >> (64 - frac_shift); + const std::uint64_t half_ulp = pow10.hi >> (1 - exp_shift); + std::uint64_t integral = half_ulp >> (63 - num_sig_bits); + const bool round_up = half_ulp > ~std::uint64_t(0) - fractional; + const bool round_down = (half_ulp >> 1) > fractional; + integral += round_up; + int digit = int(umul128_add_hi64(fractional, 10, + (std::uint64_t(1) << 63) - 1)); + const int lo = int(umul128_hi64(fractional - (half_ulp >> 1), 10)) + 1; + if (digit < lo) { + digit = lo; + } + const bool has_last_digit = !(round_up || round_down); + return {integral, dec_exp, digit & -int(has_last_digit), has_last_digit}; + } + + // Scale by 10^(-dec_exp-1) to get the shorter candidate directly and derive + // the extra digit from the fractional part. + const int dec_exp = compute_dec_exp(bin_exp, true); + const int shift = compute_exp_shift(bin_exp, dec_exp + 1) + extra_shift; + const uint128 pow10 = pow10_significands[-dec_exp - 1 - pow10_min_k]; + const uint128 p = umul192_hi128(pow10.hi, pow10.lo, bin_sig << shift); + + std::uint64_t integral = p.hi >> extra_shift; + const std::uint64_t fractional = + p.hi << (64 - extra_shift) | p.lo >> extra_shift; + const std::uint64_t even = 1 - (bin_sig & 1); + const std::uint64_t half_ulp = + (pow10.hi >> (extra_shift + 1 - shift)) + even; + const bool round_up = fractional + half_ulp < fractional; + const bool round_down = half_ulp > fractional; + integral += round_up; + + const std::size_t cell = std::size_t(p.hi >> (extra_shift - 4)) & 15; + const int digit = int((fractional + digit_offsets[cell]) >> 60); + const bool has_last_digit = !(round_up || round_down); + return {integral, dec_exp, digit & -int(has_last_digit), has_last_digit}; +} + +// The 8 digits of x < 10^8 as one byte each (values 0..9), first digit first +// in memory. +simdjson_really_inline std::uint64_t to_bcd8(std::uint64_t x) noexcept { + // abcdefgh -> abcd|efgh -> ab|cd|ef|gh -> a|b|c|d|e|f|g|h, where each step + // computes q << width | (v - q * divisor) in one multiply-add. + std::uint64_t y = + x + ((std::uint64_t(1) << 32) - 10000) * ((x * 109951163) >> 40); + y += ((std::uint64_t(1) << 16) - 100) * + (((y * 5243) >> 19) & 0x7f0000007full); + y += ((std::uint64_t(1) << 8) - 10) * + (((y * 103) >> 10) & 0xf000f000f000full); +#if SIMDJSON_IS_BIG_ENDIAN + return y; +#else + return (y & 0xff00000000000000ull) >> 56 | (y & 0x00ff000000000000ull) >> 40 | + (y & 0x0000ff0000000000ull) >> 24 | (y & 0x000000ff00000000ull) >> 8 | + (y & 0x00000000ff000000ull) << 8 | (y & 0x0000000000ff0000ull) << 24 | + (y & 0x000000000000ff00ull) << 40 | (y & 0x00000000000000ffull) << 56; +#endif } -inline std::uint64_t -compute_right_endpoint_for_shorter_interval_case(uint128 c, int beta) noexcept { - return (c.high + (c.high >> (significand_bits + 1))) >> - (total_bits - significand_bits - 1 - beta); +// Number of leading bytes of a to_bcd8 result up to its last non-zero digit. +simdjson_really_inline int count_trailing_nonzeros(std::uint64_t bcd) noexcept { +#if SIMDJSON_IS_BIG_ENDIAN + return bcd == 0 ? 0 : 8 - (__builtin_ctzll(bcd) >> 3); +#else + return (70 - clz64((bcd << 1) | 1)) >> 3; +#endif } -inline std::uint64_t -compute_round_up_for_shorter_interval_case(uint128 c, int beta) noexcept { - return ((c.high >> (total_bits - significand_bits - 2 - beta)) + 1) / 2; -} +// The 16 digits of a value below 10^16 as ASCII, first digit first. +#if SIMDJSON_TO_CHARS_NEON +struct digits16 { + uint8x16_t chars; + int trimmed_length; // number of digits up to the last non-zero one +}; -// floor(n / 10) for the shorter-interval right endpoint (n bounded so the -// single multiply below is exact). -inline std::uint64_t divide_by_pow10_1(std::uint64_t n) noexcept { - return umul128_upper64(n, std::uint64_t(1844674407370955162ull)); +// NEON version by Dougall Johnson. +simdjson_really_inline digits16 to_digits16(std::uint64_t value) noexcept { + // abcdefgh = value / 10^8, ijklmnop = value % 10^8. + const std::uint64_t abcdefgh = + std::uint64_t(umul128(value, 0xabcc77118461cefdull).hi >> 26); + const std::uint64_t ijklmnop = value - abcdefgh * 100000000; + const int32x2_t abcdefgh_ijklmnop = + vreinterpret_s32_u64(vcreate_u64(ijklmnop << 32 | abcdefgh)); + // x / 10^4 as vqdmulh (2 * x * m >> 32) followed by a shift. + const int32x2_t abcd_ijkl = vreinterpret_s32_u32(vshr_n_u32( + vreinterpret_u32_s32(vqdmulh_n_s32(abcdefgh_ijklmnop, 109951163)), 9)); + const int32x2_t efgh_abcd_mnop_ijkl_32 = + vmla_n_s32(abcdefgh_ijklmnop, abcd_ijkl, 0x10000 - 10000); + int32x4_t efgh_abcd_mnop_ijkl = vreinterpretq_s32_u32( + vshll_n_u16(vreinterpret_u16_s32(efgh_abcd_mnop_ijkl_32), 0)); + // Keeps clang from splitting the multiply-accumulate below. + __asm__("" : "+w"(efgh_abcd_mnop_ijkl)); + const int32x4_t ef_ab_mn_ij = + vqdmulhq_n_s32(efgh_abcd_mnop_ijkl, 5243 << 12); + const int16x8_t gh_ef_cd_ab_op_mn_kl_ij = vreinterpretq_s16_s32( + vmlaq_n_s32(efgh_abcd_mnop_ijkl, ef_ab_mn_ij, 65536 - 100)); + const int16x8_t high_10s = vqdmulhq_n_s16(gh_ef_cd_ab_op_mn_kl_ij, 0xce0); + const uint8x16_t unshuffled = vreinterpretq_u8_s16( + vmlaq_n_s16(gh_ef_cd_ab_op_mn_kl_ij, high_10s, 256 - 10)); + const uint8x16_t digits = vrev64q_u8(unshuffled); + const uint16x8_t is_not_zero = + vreinterpretq_u16_u8(vcgtzq_s8(vreinterpretq_s8_u8(digits))); + const std::uint64_t nonzero_mask = + vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(is_not_zero, 4)), 0); + return {vaddq_u8(digits, vdupq_n_u8('0')), + 16 - (clz64(nonzero_mask) >> 2)}; +} + +simdjson_really_inline void store16(char *p, const digits16 &d) noexcept { + vst1q_u8(reinterpret_cast(p), d.chars); +} + +simdjson_really_inline char first_char(const digits16 &d) noexcept { + return char(vgetq_lane_u8(d.chars, 0)); +} + +// Stores digits [offset, offset + 16) of the 16 digits followed by digit17 +// (bytes past digit17 are unspecified), for 1 <= offset <= 15. +simdjson_really_inline void store16_from(char *p, const digits16 &d, + char digit17, int offset) noexcept { + static const std::uint8_t iota[16] = {0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15}; + const uint8x16x2_t table = {{d.chars, vdupq_n_u8(std::uint8_t(digit17))}}; + vst1q_u8(reinterpret_cast(p), + vqtbl2q_u8(table, vaddq_u8(vld1q_u8(iota), + vdupq_n_u8(std::uint8_t(offset))))); } +#else +struct digits16 { + std::uint64_t hi; // the first 8 digits, in memory order + std::uint64_t lo; // the last 8 digits, in memory order + int trimmed_length; // number of digits up to the last non-zero one +}; -// floor(n / 1000) for the larger-divisor step (n bounded as above). -inline std::uint64_t divide_by_pow10_3(std::uint64_t n) noexcept { - return umul128_upper64(n, std::uint64_t(4722366482869645214ull)) >> 8; +simdjson_really_inline digits16 to_digits16(std::uint64_t value) noexcept { + const std::uint64_t hi = value / 100000000; + const std::uint64_t lo = value - hi * 100000000; + constexpr std::uint64_t zeros = 0x3030303030303030ull; + const std::uint64_t hi_bcd = to_bcd8(hi); + if (lo == 0) { + return {hi_bcd + zeros, zeros, count_trailing_nonzeros(hi_bcd)}; + } + const std::uint64_t lo_bcd = to_bcd8(lo); + return {hi_bcd + zeros, lo_bcd + zeros, 8 + count_trailing_nonzeros(lo_bcd)}; } -// Returns whether n is divisible by 10^kappa (= 100) and divides n by it. -inline bool check_divisibility_and_divide_by_pow10_kappa(std::uint64_t &n) noexcept { - // magic number for division by 100 (kappa == 2). - const std::uint32_t prod = std::uint32_t(n) * std::uint32_t(656); - const bool result = (prod & 0xffffu) < 656u; - n = std::uint64_t(prod >> 16); - return result; +simdjson_really_inline void store16(char *p, const digits16 &d) noexcept { + std::memcpy(p, &d.hi, 8); + std::memcpy(p + 8, &d.lo, 8); } -// Strip trailing decimal zeros from significand, bumping exponent accordingly. -// Branchless search; constants from the Dragonbox reference. -inline void remove_trailing_zeros(std::uint64_t &significand, int &exponent) noexcept { - std::uint64_t r = rotr64(significand * std::uint64_t(28999941890838049ull), 8); - bool b = r < std::uint64_t(184467440738ull); - int s = b ? 1 : 0; - significand = b ? r : significand; - - r = rotr64(significand * std::uint64_t(182622766329724561ull), 4); - b = r < std::uint64_t(1844674407370956ull); - s = s * 2 + (b ? 1 : 0); - significand = b ? r : significand; - - r = rotr64(significand * std::uint64_t(10330176681277348905ull), 2); - b = r < std::uint64_t(184467440737095517ull); - s = s * 2 + (b ? 1 : 0); - significand = b ? r : significand; - - r = rotr64(significand * std::uint64_t(14757395258967641293ull), 1); - b = r < std::uint64_t(1844674407370955162ull); - s = s * 2 + (b ? 1 : 0); - significand = b ? r : significand; - - exponent += s; +simdjson_really_inline char first_char(const digits16 &d) noexcept { +#if SIMDJSON_IS_BIG_ENDIAN + return char(d.hi >> 56); +#else + return char(d.hi); +#endif } -// Dragonbox core: shortest (significand, exponent) such that -// value == significand * 10^exponent -// for a finite, positive, non-zero binary64 value, decomposed into its raw -// significand bits and biased exponent bits. -struct decimal_fp { - std::uint64_t significand; - int exponent; -}; - -inline decimal_fp to_decimal(std::uint64_t binary_significand, - int binary_exponent) noexcept { - const bool is_even = (binary_significand % 2 == 0); - std::uint64_t two_fc = binary_significand * 2; - - // Is the input a normal number? - if (binary_exponent != 0) { - binary_exponent += exponent_bias - significand_bits; - - // Shorter interval case; proceed like Schubfach. - if (two_fc == 0) { - const int minus_k = - floor_log10_pow2_minus_log10_4_over_3(binary_exponent); - const int beta = binary_exponent + floor_log2_pow10(-minus_k); - const uint128 c = cache[-minus_k - cache_min_k]; - - std::uint64_t xi = - compute_left_endpoint_for_shorter_interval_case(c, beta); - const std::uint64_t zi = - compute_right_endpoint_for_shorter_interval_case(c, beta); - - // If the left endpoint is not an integer, increase it. (Both endpoints - // are always included since the significand is even.) - if (!(binary_exponent >= - case_shorter_interval_left_endpoint_lower_threshold && - binary_exponent <= - case_shorter_interval_left_endpoint_upper_threshold)) { - ++xi; - } - - // Try the bigger divisor. - std::uint64_t decimal_significand = divide_by_pow10_1(zi); - if (decimal_significand * 10 >= xi) { - int decimal_exponent = minus_k + 1; - remove_trailing_zeros(decimal_significand, decimal_exponent); - return {decimal_significand, decimal_exponent}; - } - - // Otherwise, compute the round-up of y. - decimal_significand = - compute_round_up_for_shorter_interval_case(c, beta); - // On a tie, choose the even one. - if ((decimal_significand % 2 != 0) && - binary_exponent >= shorter_interval_tie_lower_threshold && - binary_exponent <= shorter_interval_tie_upper_threshold) { - --decimal_significand; - } else if (decimal_significand < xi) { - ++decimal_significand; - } - return {decimal_significand, minus_k}; - } - - // Normal interval case. - two_fc |= (std::uint64_t(1) << (significand_bits + 1)); - } else { - // Subnormal number: normal interval case. - binary_exponent = min_exponent - significand_bits; - } - - // Step 1: Schubfach multiplier calculation. - const int minus_k = floor_log10_pow2(binary_exponent) - kappa; - const uint128 c = cache[-minus_k - cache_min_k]; - const int beta = binary_exponent + floor_log2_pow10(-minus_k); - - const std::uint64_t deltai = compute_delta(c, beta); - const compute_mul_result z_result = - compute_mul((two_fc | 1) << beta, c); - - // Step 2: Try larger divisor; remove trailing zeros if necessary. - std::uint64_t decimal_significand = divide_by_pow10_3(z_result.integer_part); - std::uint64_t r = - z_result.integer_part - std::uint64_t(big_divisor) * decimal_significand; - - do { - if (r < deltai) { - // Exclude the right endpoint if necessary. - if ((r | std::uint64_t(!z_result.is_integer) | std::uint64_t(is_even)) == - 0) { - --decimal_significand; - r = big_divisor; - break; - } - } else if (r > deltai) { - break; - } else { - // r == deltai; compare fractional parts. - const compute_mul_parity_result x_result = - compute_mul_parity(two_fc - 1, c, beta); - if (!(x_result.parity | (x_result.is_integer & is_even))) { - break; - } - } - - int decimal_exponent = minus_k + kappa + 1; - remove_trailing_zeros(decimal_significand, decimal_exponent); - return {decimal_significand, decimal_exponent}; - } while (false); - - // Step 3: Find the significand with the smaller divisor. - decimal_significand *= 10; - - std::uint64_t dist = r - (deltai / 2) + (small_divisor / 2); - const bool approx_y_parity = ((dist ^ (small_divisor / 2)) & 1) != 0; - - const bool divisible_by_small_divisor = - check_divisibility_and_divide_by_pow10_kappa(dist); - - decimal_significand += dist; - - if (divisible_by_small_divisor) { - const compute_mul_parity_result y_result = - compute_mul_parity(two_fc, c, beta); - if (y_result.parity != approx_y_parity) { - --decimal_significand; - } else if ((decimal_significand % 2) != 0 && y_result.is_integer) { - // On a tie (y is an integer), choose the even one. - --decimal_significand; - } - } - - return {decimal_significand, minus_k + kappa}; +// Stores digits [offset, offset + 16) of the 16 digits followed by digit17 +// (bytes past digit17 are unspecified), for 1 <= offset <= 15. +simdjson_really_inline void store16_from(char *p, const digits16 &d, + char digit17, int offset) noexcept { +#if defined(__SIZEOF_INT128__) + const unsigned shift = 8 * unsigned(offset); + const __uint128_t last = std::uint8_t(digit17); +#if SIMDJSON_IS_BIG_ENDIAN + const __uint128_t window = __uint128_t(d.hi) << 64 | d.lo; + const __uint128_t tail = window << shift | last << (shift - 8); +#else + const __uint128_t window = __uint128_t(d.lo) << 64 | d.hi; + const __uint128_t tail = window >> shift | last << (128 - shift); +#endif + std::memcpy(p, &tail, 16); +#else + char window[32] = {}; + store16(window, d); + window[16] = digit17; + std::memcpy(p, window + offset, 16); +#endif } +#endif -/*! -Fills buf with the shortest decimal digits of 'value' (which must be finite, -positive and non-zero), sets len to the number of digits, and decimal_exponent -so that value == (buf, interpreted as an integer) * 10^decimal_exponent. -This mirrors the contract of the previous grisu2() entry point. -*/ -inline void dragonbox(char *buf, int &len, int &decimal_exponent, - double value) { - std::uint64_t bits; - std::memcpy(&bits, &value, sizeof(bits)); - const std::uint64_t binary_significand = - bits & ((std::uint64_t(1) << significand_bits) - 1); - const int binary_exponent = - int((bits >> significand_bits) & 0x7ff); - - const decimal_fp dec = to_decimal(binary_significand, binary_exponent); - - // Convert the decimal significand to digits: - // 1) Proceed 2 digits at a time (s % 100) via a 00..99 lookup table - // (see Alexandrescu, "Three Optimization Tips for C++", 2012), - // 2) Digits come out least-significant first, writing them back-to-front - // with p = tmp + sizeof(tmp); to avoid reversal pass - // 3) Proceed remaining digits after loop to avoid branchs inside it - // 4) memcpy digits to char* buf (inside function input) +// Writes e+NN, e-NN or e+NNN (at least two exponent digits, as printf) as one +// 8-byte store; the bytes past the exponent are unspecified. +simdjson_really_inline char *write_exponent(char *p, int e) noexcept { static const char digits2[201] = "0001020304050607080910111213141516171819" "2021222324252627282930313233343536373839" "4041424344454647484950515253545556575859" "6061626364656667686970717273747576777879" "8081828384858687888990919293949596979899"; - // Digit area is 24; +16 padding lets us always memcpy 16 (+1) bytes with a - // compile-time size so the compiler inlines (no libc size-class branches). - // Callers must provide to_chars_buffer_size (40) bytes for the same reason. - constexpr int digit_area = 24; - char tmp[digit_area + 16]; - char *p = tmp + digit_area; // write backward - std::uint64_t s = dec.significand; - while (s >= 100) { - const std::uint32_t idx = static_cast(s % 100) * 2; - s /= 100; - p -= 2; - p[0] = digits2[idx]; - p[1] = digits2[idx + 1]; - } - if (s >= 10) { - const std::uint32_t idx = static_cast(s) * 2; - p -= 2; - p[0] = digits2[idx]; - p[1] = digits2[idx + 1]; - } else { - *--p = static_cast('0' + s); - } - // Fixed-size copy: double has at most 17 significant digits. - std::memcpy(buf, p, 16); - buf[16] = p[16]; - len = static_cast(tmp + digit_area - p); - decimal_exponent = dec.exponent; -} - -/*! -@brief appends a decimal representation of e to buf -@return a pointer to the element following the exponent. -@pre -1000 < e < 1000 -*/ -inline char *append_exponent(char *buf, int e) { - - bool isNegative = e < 0; - e = isNegative ? -e : e; - *buf++ = isNegative ? '-' : '+'; - - auto k = static_cast(e); - if (k < 100) { - // Always print at least two digits in the exponent. - // This is for compatibility with printf("%g"). - *buf++ = static_cast('0' + k / 10); - k %= 10; - *buf++ = static_cast('0' + k); - } else { - *buf++ = static_cast('0' + k / 100); - k %= 100; - *buf++ = static_cast('0' + k / 10); - k %= 10; - *buf++ = static_cast('0' + k); - } - - return buf; -} - -/*! -@brief prettify v = buf * 10^decimal_exponent -If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point -notation. Otherwise it will be printed in exponential notation. -@pre min_exp < 0 -@pre max_exp > 0 -*/ -inline char *format_buffer(char *buf, int len, int decimal_exponent, - int min_exp, int max_exp) { - - const int k = len; - const int n = len + decimal_exponent; - - // v = buf * 10^(n-k) - // k is the length of the buffer (number of decimal digits) - // n is the position of the decimal point relative to the start of the buffer. - - // All mem* sizes below are compile-time constants so the compiler inlines - // them as plain loads/stores. That requires over-writing past the logical - // string length; callers must reserve to_chars_buffer_size (40) bytes. - // Logical output is still bounded by ~24 characters; only the returned - // pointer reflects the true length. - - if (k <= n && n <= max_exp) { - // digits[000] - // len <= max_exp + 2 - std::memset(buf + k, '0', 16); - // Make it look like a floating-point number (#362, #378) - buf[n + 0] = '.'; - buf[n + 1] = '0'; - return buf + (static_cast(n)) + 2; - } - - if (0 < n && n <= max_exp) { - // dig.its - // len <= max_digits10 + 1 - // Shift the fractional digits one place right via a temp (overlap). - char shifted[16]; - std::memcpy(shifted, buf + static_cast(n), 16); - std::memcpy(buf + (static_cast(n) + 1), shifted, 16); - buf[n] = '.'; - return buf + (static_cast(k) + 1U); - } - - if (min_exp < n && n <= 0) { - // 0.[000]digits - // With kMinExp = -4, n is in {-3,-2,-1,0}, so pad = -n is 0..3. - // len <= 2 + (-min_exp - 1) + max_digits10 - char digits[17]; - std::memcpy(digits, buf, 17); - const size_t pad = static_cast(-n); // 0..3 - buf[0] = '0'; - buf[1] = '.'; - // Fixed upper bound on leading zeros; only the first `pad` matter. - std::memset(buf + 2, '0', 4); - std::memcpy(buf + 2 + pad, digits, 17); - return buf + (2U + pad + static_cast(k)); - } - - if (k == 1) { - // dE+123 - // len <= 1 + 5 - buf += 1; - } else { - // d.igitsE+123 - // len <= max_digits10 + 1 + 5 - // k-1 <= 16 for double; fixed-size shift via temp (overlap). - char shifted[16]; - std::memcpy(shifted, buf + 1, 16); - std::memcpy(buf + 2, shifted, 16); - buf[1] = '.'; - buf += 1 + static_cast(k); - } - - *buf++ = 'e'; - return append_exponent(buf, n - 1); + const std::uint64_t sign = e < 0 ? '-' : '+'; + const std::uint32_t k = std::uint32_t(e < 0 ? -e : e); // < 1000 + const std::uint32_t hundreds = (k * 5243) >> 19; + const std::uint32_t rest = k - hundreds * 100; + std::uint16_t two; + std::memcpy(&two, digits2 + rest * 2, 2); + // Three digits are built, then the leading one is shifted out when k < 100. + const std::uint32_t drop = 8 * std::uint32_t(k < 100); +#if SIMDJSON_IS_BIG_ENDIAN + const std::uint32_t digits = ((('0' + hundreds) << 24) | (std::uint32_t(two) << 8)) << drop; + const std::uint64_t text = std::uint64_t('e') << 56 | sign << 48 | std::uint64_t(digits) << 16; +#else + const std::uint32_t digits = (('0' + hundreds) | (std::uint32_t(two) << 8)) >> drop; + const std::uint64_t text = std::uint64_t('e') | sign << 8 | std::uint64_t(digits) << 16; +#endif + std::memcpy(p, &text, 8); + return p + 5 - int(drop >> 3); } -} // NS dtoa_impl +} // namespace dtoa_impl /*! The format of the resulting decimal representation is similar to printf's %g @@ -4770,45 +4655,91 @@ format. Returns an iterator pointing past-the-end of the decimal representation. @note The input number must be finite, i.e. NaN's and Inf's are not supported. @note The buffer must have at least to_chars_buffer_size (40) writable bytes. Only ~24 characters are ever part of the logical result, but fixed-size - 16/17-byte mem* over-writes require the extra scratch for safety. + 8/16-byte stores require the extra scratch. @note The result is NOT null-terminated. */ char *to_chars(char *first, const char *last, double value) { + using namespace dtoa_impl; static_cast(last); // maybe unused - fix warning - bool negative = std::signbit(value); - if (negative) { - value = -value; - *first++ = '-'; - } - - if (value == 0) // +-0 - { - *first++ = '0'; - // Make it look like a floating-point number (#362, #378) - *first++ = '.'; - *first++ = '0'; - return first; - } - // Compute v = buffer * 10^decimal_exponent. - // The decimal digits are stored in the buffer, which needs to be interpreted - // as an unsigned decimal integer. - // len is the length of the buffer, i.e. the number of decimal digits. - int len = 0; - int decimal_exponent = 0; - dtoa_impl::dragonbox(first, len, decimal_exponent, value); - // Format the buffer like printf("%.*g", prec, value) - constexpr int kMinExp = -4; - constexpr int kMaxExp = std::numeric_limits::digits10; - - return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, - kMaxExp); + std::uint64_t bits; + std::memcpy(&bits, &value, sizeof(bits)); + *first = '-'; + first += bits >> 63; + const std::uint64_t bin_sig = bits & (implicit_bit - 1); + const int raw_exp = int((bits >> num_sig_bits) & 0x7ff); + + shortest_decimal dec; + if (simdjson_unlikely(raw_exp == 0)) { + if (bin_sig == 0) { + // Make it look like a floating-point number (#362, #378) + std::memcpy(first, "0.0", 3); + return first + 3; + } + // A subnormal: the power of ten comes from the exponent alone, so pad the + // short significand to the 15 digits the layout below expects. + dec = to_decimal(bin_sig, 1, true); + int num_digits = + compute_dec_exp(63 - clz64(dec.sig | 1), true) + (dec.sig != 0); + num_digits += dec.sig >= pow10s[num_digits]; + const int num_zeros = 17 - 3 - num_digits; + if (num_zeros >= 0) { + const std::uint64_t sig = dec.sig * 10 + std::uint64_t(dec.last_digit); + dec = {sig * pow10s[num_zeros], dec.exp - num_zeros - 1, 0, false}; + } + } else { + dec = to_decimal(bin_sig | implicit_bit, raw_exp, bin_sig != 0); + } + + // dec.sig has 15 or 16 digits. Make it exactly 16 by appending the extra + // digit when it has 15, so the first significant digit is always first. + const bool has_extra_digit = dec.sig >= pow10s[15]; + const int last_digit = dec.last_digit; + const std::uint64_t sig16 = + has_extra_digit ? dec.sig : dec.sig * 10 + std::uint64_t(last_digit); + const char digit17 = char('0' + (has_extra_digit ? last_digit : 0)); + // Decimal exponent of the first digit. + const int lead_exp = dec.exp + 15 + int(has_extra_digit); + + const digits16 digits = to_digits16(sig16); + // All 16 or 17 digits when there is a last digit, else up to the last + // non-zero one. Mask arithmetic, as a branch here mispredicts on random + // inputs. + const int all_digits = -int(dec.has_last_digit); + const int num_digits = (digits.trimmed_length & ~all_digits) | + ((16 + int(has_extra_digit)) & all_digits); + + // Fixed notation for 1e-4 <= |value| < 1e15, else exponential. Every + // store below is a fixed-size copy, hence the 40-byte scratch requirement. + const int point = lead_exp + 1; // digits before the decimal point + if (point >= 1 && point <= 15) { + // dig.its or digits[000].0: the digits are followed by '0' bytes past the + // last significant one. Write them, then write them again from position + // point on, one byte to the right, and put the point in the gap. + store16(first, digits); + store16_from(first + point + 1, digits, digit17, point); + first[point] = '.'; + return first + 1 + (num_digits > point ? num_digits : point + 1); + } + if (point <= 0 && point > -4) { + // 0.[000]digits + std::memcpy(first, "0.000000", 8); + char *p = first + 2 - point; + store16(p, digits); + p[16] = digit17; + return p + num_digits; + } + // d[.igits]e+NN + store16(first + 1, digits); + first[17] = digit17; + first[0] = first_char(digits); + first[1] = '.'; + char *p = first + num_digits + (num_digits > 1 ? 1 : 0); + return write_exponent(p, lead_exp); } } // NS internal } // NS simdjson #endif // SIMDJSON_SRC_TO_CHARS_CPP - - /* end file to_chars.cpp */ /* including from_chars.cpp: #include */ /* begin file from_chars.cpp */ @@ -10228,6 +10159,13 @@ simdjson_result::get(T &value) && noexcept { return std::forward>(*this).get(value); } +template +simdjson_warn_unused simdjson_inline simdjson_result +simdjson_result::default_if_missing(T default_value) && noexcept { + if (error() == NO_SUCH_FIELD) { return simdjson_result(std::move(default_value)); } + return std::move(*this); +} + template simdjson_inline error_code simdjson_result::error() const noexcept { return internal::simdjson_result_base::error(); @@ -12312,6 +12250,115 @@ class atomic_ptr { /* skipped duplicate #include "simdjson/base.h" */ /* skipped duplicate #include "simdjson/error.h" */ +/* including simdjson/buffer_allocator.h: #include "simdjson/buffer_allocator.h" */ +/* begin file simdjson/buffer_allocator.h */ +#ifndef SIMDJSON_BUFFER_ALLOCATOR_H +#define SIMDJSON_BUFFER_ALLOCATOR_H + +/* skipped duplicate #include "simdjson/base.h" */ + +#include +#include + +namespace simdjson { + +/** + * Allocates the buffers that a parser keeps between documents and that grow + * with the largest document it parses: the structural indexes, the On-Demand + * string buffer, and the DOM tape and string buffer. + * + * Both functions must be noexcept. allocate returns memory aligned at least + * as malloc would align it, or nullptr on failure, in which case the parser + * returns MEMALLOC and keeps its previous buffers. deallocate receives the + * pointer, the size that was requested and the context. + * + * A parser allocates only when it grows, so a reused parser rarely calls the + * allocator. The allocator, and its context, must outlive every parser and + * document that holds memory from it. + */ +struct buffer_allocator { + void *(*allocate)(void *context, size_t size) noexcept; + void (*deallocate)(void *context, void *pointer, size_t size) noexcept; + void *context; +}; + +namespace internal { + +/** + * @private An owning array of trivial elements, from a buffer_allocator or, + * without one, from new[]. It frees itself through what allocated it. + */ +template class allocated_array { +public: + allocated_array() noexcept = default; + allocated_array(const allocated_array &) = delete; + allocated_array &operator=(const allocated_array &) = delete; + allocated_array(allocated_array &&other) noexcept + : data_{other.data_}, size_{other.size_}, allocator_{other.allocator_} { + other.data_ = nullptr; + other.size_ = 0; + other.allocator_ = nullptr; + } + allocated_array &operator=(allocated_array &&other) noexcept { + if (this != &other) { + reset(); + data_ = other.data_; + size_ = other.size_; + allocator_ = other.allocator_; + other.data_ = nullptr; + other.size_ = 0; + other.allocator_ = nullptr; + } + return *this; + } + ~allocated_array() noexcept { reset(); } + + /** Replace the content by count uninitialized elements; false on failure. */ + bool allocate(size_t count, const buffer_allocator *allocator) noexcept { + reset(); + if (allocator) { + if (count > size_t(-1) / sizeof(T)) { + return false; + } + data_ = static_cast(allocator->allocate(allocator->context, count * sizeof(T))); + } else { + data_ = new (std::nothrow) T[count]; + } + if (!data_) { + return false; + } + size_ = count; + allocator_ = allocator; + return true; + } + void reset() noexcept { + if (!data_) { + return; + } + if (allocator_) { + allocator_->deallocate(allocator_->context, data_, size_ * sizeof(T)); + } else { + delete[] data_; + } + data_ = nullptr; + size_ = 0; + allocator_ = nullptr; + } + simdjson_inline T *get() const noexcept { return data_; } + simdjson_inline T &operator[](size_t index) const noexcept { return data_[index]; } + simdjson_inline explicit operator bool() const noexcept { return data_ != nullptr; } + +private: + T *data_{nullptr}; + size_t size_{0}; + const buffer_allocator *allocator_{nullptr}; +}; + +} // namespace internal +} // namespace simdjson + +#endif // SIMDJSON_BUFFER_ALLOCATOR_H +/* end file simdjson/buffer_allocator.h */ #include namespace simdjson { @@ -12498,9 +12545,15 @@ class dom_parser_implementation { /** Number of structural indices passed from stage 1 to stage 2 */ uint32_t n_structural_indexes{0}; /** Structural indices passed from stage 1 to stage 2 */ - std::unique_ptr structural_indexes{}; + allocated_array structural_indexes{}; + /** Allocates structural_indexes when set_capacity grows them; nullptr uses new[]. */ + const buffer_allocator *allocator{nullptr}; /** Next structural index to parse */ uint32_t next_structural_index{0}; + /** Buffer passed to stage 1 (also set by the lone-atom fast path). */ + const uint8_t *buf{}; + /** Length passed to stage 1. */ + size_t len{0}; /** * The largest document this parser can support without reallocating. @@ -12575,6 +12628,76 @@ class dom_parser_implementation { simdjson_inline dom_parser_implementation &operator=(const dom_parser_implementation &other) noexcept = delete; }; // class dom_parser_implementation +// Stage-1 fast path for a single JSON atom (number / true / false / null) +// surrounded only by ASCII whitespace. Writes the one-entry structural tape +// and returns SUCCESS, returns EMPTY for an all-whitespace buffer, or +// returns UNINITIALIZED if the buffer is not that shape (caller must run +// the full indexer). json_structural_indexer::index calls it before the +// SIMD loop. +simdjson_never_inline error_code try_stage1_lone_atom(dom_parser_implementation &parser, const uint8_t *buf, size_t len) noexcept { + auto is_json_ws = [](uint8_t c) noexcept { + return c == ' ' || c == '\t' || c == '\n' || c == '\r'; + }; + size_t i = 0; + while (i < len && is_json_ws(buf[i])) { i++; } + if (i == len) { return EMPTY; } + const size_t atom = i; + const uint8_t c = buf[i]; + if (c >= 0x80 || c == '"' || c == '{' || c == '[' || c == '}' || c == ']' || c == ':' || c == ',') { + return UNINITIALIZED; + } + if (c == 't') { + if (i + 4 > len || buf[i+1] != 'r' || buf[i+2] != 'u' || buf[i+3] != 'e') { return UNINITIALIZED; } + i += 4; + } else if (c == 'f') { + if (i + 5 > len || buf[i+1] != 'a' || buf[i+2] != 'l' || buf[i+3] != 's' || buf[i+4] != 'e') { return UNINITIALIZED; } + i += 5; + } else if (c == 'n') { + if (i + 4 > len || buf[i+1] != 'u' || buf[i+2] != 'l' || buf[i+3] != 'l') { return UNINITIALIZED; } + i += 4; + } else if (c == '-' || (c >= '0' && c <= '9')) { + if (c == '-') { + i++; + if (i == len) { return UNINITIALIZED; } + } + if (buf[i] == '0') { + i++; + } else if (buf[i] >= '1' && buf[i] <= '9') { + i++; + while (i < len && buf[i] >= '0' && buf[i] <= '9') { i++; } + } else { + return UNINITIALIZED; + } + if (i < len && buf[i] == '.') { + i++; + if (i == len || buf[i] < '0' || buf[i] > '9') { return UNINITIALIZED; } + while (i < len && buf[i] >= '0' && buf[i] <= '9') { i++; } + } + if (i < len && (buf[i] == 'e' || buf[i] == 'E')) { + i++; + if (i < len && (buf[i] == '+' || buf[i] == '-')) { i++; } + if (i == len || buf[i] < '0' || buf[i] > '9') { return UNINITIALIZED; } + while (i < len && buf[i] >= '0' && buf[i] <= '9') { i++; } + } + } else { + return UNINITIALIZED; + } + if (i < len && !is_json_ws(buf[i])) { return UNINITIALIZED; } + while (i < len) { + if (!is_json_ws(buf[i])) { return UNINITIALIZED; } + i++; + } + parser.buf = buf; + parser.len = len; + parser.structural_indexes[0] = uint32_t(atom); + parser.n_structural_indexes = 1; + parser.structural_indexes[1] = uint32_t(len); + parser.structural_indexes[2] = uint32_t(len); + parser.structural_indexes[3] = 0; + parser.next_structural_index = 0; + return SUCCESS; +} + simdjson_inline dom_parser_implementation::dom_parser_implementation() noexcept = default; simdjson_inline dom_parser_implementation::dom_parser_implementation(dom_parser_implementation &&other) noexcept = default; simdjson_inline dom_parser_implementation &dom_parser_implementation::operator=(dom_parser_implementation &&other) noexcept = default; @@ -12919,6 +13042,33 @@ enum instruction_set { /* skipped duplicate #include "simdjson/internal/dom_parser_implementation.h" */ /* skipped duplicate #include "simdjson/internal/jsoncharutils_tables.h" */ /* skipped duplicate #include "simdjson/internal/numberparsing_tables.h" */ +/* including simdjson/internal/numberparsing.h: #include "simdjson/internal/numberparsing.h" */ +/* begin file simdjson/internal/numberparsing.h */ +#ifndef SIMDJSON_INTERNAL_NUMBERPARSING_H +#define SIMDJSON_INTERNAL_NUMBERPARSING_H + +/* skipped duplicate #include "simdjson/base.h" */ + +namespace simdjson { +namespace internal { + +/** + * The value of the eight ASCII digits in val, the first digit in the lowest + * byte (little-endian). Only the low four bits of each byte count, so zero + * bytes act as leading zeros. The scalar parse_eight_digits_unrolled. + * credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ + */ +simdjson_inline uint32_t parse_eight_digits_swar(uint64_t val) { + val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; + val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; + return static_cast((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); +} + +} // namespace internal +} // namespace simdjson + +#endif // SIMDJSON_INTERNAL_NUMBERPARSING_H +/* end file simdjson/internal/numberparsing.h */ /* including simdjson/internal/simdprune_tables.h: #include "simdjson/internal/simdprune_tables.h" */ /* begin file simdjson/internal/simdprune_tables.h */ #ifndef SIMDJSON_INTERNAL_SIMDPRUNE_TABLES_H @@ -12943,6 +13093,56 @@ extern SIMDJSON_DLLIMPORTEXPORT const uint64_t thintable_epi8[256]; #endif // SIMDJSON_INTERNAL_SIMDPRUNE_TABLES_H /* end file simdjson/internal/simdprune_tables.h */ +/* including simdjson/internal/partial_load.h: #include "simdjson/internal/partial_load.h" */ +/* begin file simdjson/internal/partial_load.h */ +#ifndef SIMDJSON_INTERNAL_PARTIAL_LOAD_H +#define SIMDJSON_INTERNAL_PARTIAL_LOAD_H + +/* skipped duplicate #include "simdjson/base.h" */ + +#include +#include + +namespace simdjson { +namespace internal { + +// shift_tail_mask + 16 - n holds the byte indexes that move the last n bytes +// of a 16-byte vector to its front, followed by indexes with the high bit set. +alignas(16) static const uint8_t shift_tail_mask[32] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 +}; + +// Loads the n < 16 bytes at ptr, and only those, into two little-endian +// words. The other bytes are set to fill. +simdjson_inline void load_small_words(const uint8_t *ptr, size_t n, uint8_t fill, uint64_t &lo, uint64_t &hi) { + const uint64_t fills = 0x0101010101010101 * fill; + lo = fills; + hi = fills; + if (n >= 8) { + std::memcpy(&lo, ptr, 8); + if (n > 8) { + // The 8 bytes ending at ptr + n overlap lo: keep their last n - 8. + uint64_t tail; + std::memcpy(&tail, ptr + n - 8, 8); + hi = (tail >> (8 * (16 - n))) | (fills << (8 * (n - 8))); + } + } else if (n >= 4) { + uint32_t first, last; + std::memcpy(&first, ptr, 4); + std::memcpy(&last, ptr + n - 4, 4); + lo = first | (uint64_t(last) << (8 * (n - 4))) | (fills << (8 * n)); + } else if (n > 0) { + lo = ptr[0] | (uint64_t(ptr[n / 2]) << (8 * (n / 2))) | (uint64_t(ptr[n - 1]) << (8 * (n - 1))) + | (fills << (8 * n)); + } +} + +} // namespace internal +} // namespace simdjson + +#endif // SIMDJSON_INTERNAL_PARTIAL_LOAD_H +/* end file simdjson/internal/partial_load.h */ #endif // SIMDJSON_GENERIC_DEPENDENCIES_H /* end file simdjson/generic/dependencies.h */ /* including generic/dependencies.h: #include */ @@ -13032,6 +13232,7 @@ class tape_ref; #endif // SIMDJSON_DOM_BASE_H /* end file simdjson/dom/base.h */ +/* skipped duplicate #include "simdjson/buffer_allocator.h" */ #include @@ -13084,13 +13285,13 @@ class document { bool dump_raw_tape(std::ostream &os) const noexcept; /** @private Structural values. */ - std::unique_ptr tape{}; + internal::allocated_array tape{}; /** @private String values. * * Should be at least byte_capacity. */ - std::unique_ptr string_buf{}; + internal::allocated_array string_buf{}; /** @private Allocate memory to support * input JSON documents of up to len bytes. * @@ -13101,8 +13302,10 @@ class document { * can you use this function to increase * or lower the amount of allocated memory. * Passing zero clears the memory. + * + * The buffers come from allocator, or from new[] when it is nullptr. */ - error_code allocate(size_t len) noexcept; + error_code allocate(size_t len, const buffer_allocator *allocator = nullptr) noexcept; /** @private Capacity in bytes, in terms * of how many bytes of input JSON we can * support. @@ -14403,6 +14606,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -14417,14 +14621,11 @@ namespace arm64 { namespace numberparsing { // we don't have SSE, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -14468,6 +14669,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -14616,6 +14818,26 @@ namespace { static simdjson_inline uint8x16_t splat(uint8_t _value) { return vmovq_n_u8(_value); } static simdjson_inline uint8x16_t zero() { return vdupq_n_u8(0); } static simdjson_inline uint8x16_t load(const uint8_t* values) { return vld1q_u8(values); } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline uint8x16_t load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const uint8x16_t window = vld1q_u8(ptr + n - 16); + const uint8x16_t shuffle = vld1q_u8(internal::shift_tail_mask + 16 - n); + // vqtbl1q_u8 zeroes the bytes whose index is out of range. + const uint8x16_t filler = vandq_u8(vcgeq_u8(shuffle, vdupq_n_u8(16)), vdupq_n_u8(fill)); + return vorrq_u8(vqtbl1q_u8(window, shuffle), filler); + } +#if SIMDJSON_IS_BIG_ENDIAN + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return vld1q_u8(block); +#else + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return vcombine_u8(vcreate_u8(lo), vcreate_u8(hi)); +#endif + } simdjson_inline simd8(const uint8x16_t _value) : base_u8(_value) {} // Zero constructor @@ -15407,10 +15629,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -15458,8 +15676,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -15653,6 +15871,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -16244,6 +16463,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -16297,19 +16525,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -16317,7 +16563,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -16698,10 +16946,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -16748,10 +16994,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -16803,10 +17047,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -16848,10 +17090,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -17731,6 +17971,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -17745,14 +17986,11 @@ namespace arm64 { namespace numberparsing { // we don't have SSE, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -17796,6 +18034,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -17944,6 +18183,26 @@ namespace { static simdjson_inline uint8x16_t splat(uint8_t _value) { return vmovq_n_u8(_value); } static simdjson_inline uint8x16_t zero() { return vdupq_n_u8(0); } static simdjson_inline uint8x16_t load(const uint8_t* values) { return vld1q_u8(values); } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline uint8x16_t load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const uint8x16_t window = vld1q_u8(ptr + n - 16); + const uint8x16_t shuffle = vld1q_u8(internal::shift_tail_mask + 16 - n); + // vqtbl1q_u8 zeroes the bytes whose index is out of range. + const uint8x16_t filler = vandq_u8(vcgeq_u8(shuffle, vdupq_n_u8(16)), vdupq_n_u8(fill)); + return vorrq_u8(vqtbl1q_u8(window, shuffle), filler); + } +#if SIMDJSON_IS_BIG_ENDIAN + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return vld1q_u8(block); +#else + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return vcombine_u8(vcreate_u8(lo), vcreate_u8(hi)); +#endif + } simdjson_inline simd8(const uint8x16_t _value) : base_u8(_value) {} // Zero constructor @@ -18538,6 +18797,14 @@ struct buf_block_reader { * with full-width stores that the loads can forward from. */ simdjson_inline size_t get_remainder_padded(uint8_t *dst) const; + /** + * Like get_remainder, but reads only the input bytes: no padding is needed. + * + * The block is put together in vector registers and written with + * full-width stores, so that the loads that read it back are forwarded from + * the stores (see get_remainder_padded). + */ + simdjson_inline size_t get_remainder_unpadded(uint8_t *dst) const; simdjson_inline void advance(); private: const uint8_t *buf; @@ -18602,6 +18869,25 @@ simdjson_inline size_t buf_block_reader::get_remainder_padded(uint8_t return remaining; } +template +simdjson_inline size_t buf_block_reader::get_remainder_unpadded(uint8_t *dst) const { + const size_t remaining = len - idx; + constexpr size_t width = sizeof(simd::simd8); + for (size_t off = 0; off < STEP_SIZE; off += width) { + if (off + width <= remaining) { + const simd::simd8 v = simd::simd8::load(buf + idx + off); + v.store(dst + off); + } else if (off < remaining) { + const simd::simd8 v = simd::simd8::load_partial(buf + idx + off, remaining - off, buf, 0x20); + v.store(dst + off); + } else { + const simd::simd8 v = simd::simd8::splat(0x20); + v.store(dst + off); + } + } + return remaining; +} + template simdjson_inline void buf_block_reader::advance() { idx += STEP_SIZE; @@ -19520,11 +19806,9 @@ simdjson_inline uint32_t find_next_document_index_json_sequence( // Phase 2: Determine batch boundaries based on RS positions if (is_final) { - // Final batch: all documents are complete (last one ends at EOF). - // In json_sequence mode, RS markers define document boundaries, so all - // remaining structurals form complete documents. Return them all directly. - // (Calling find_next_document_index() would fail for scalar documents.) - return parser.n_structural_indexes; + // A cut number must not be parsed into padding the caller does not + // initialize. Leave that record to truncated_bytes(), as streaming_final does. + return find_next_document_index(parser); } // Partial batch: need to find complete documents only. @@ -19643,9 +19927,13 @@ simdjson_inline uint32_t filter_comma_delimited( // A document ending with a root comma is complete. if (root_comma_count == 0) { // No root commas found; we cannot confirm any document is complete. - // The whole batch might be one incomplete document. - // Return DOCUMENT_TOO_LARGE if content was found (write_idx > 0), 0 if only commas. - return (parser.n_structural_indexes > 0) ? DOCUMENT_TOO_LARGE : 0; + // The whole batch might be one incomplete document. If white space comes + // before it, a batch that starts at the document may hold it. + if (parser.structural_indexes[0] > 0) { + next_batch_start = parser.structural_indexes[0]; + return 0; + } + return DOCUMENT_TOO_LARGE; } // We have at least one root comma. Documents before the last comma are complete. @@ -19714,7 +20002,12 @@ class json_minifier { simdjson_inline void json_minifier::next(const simd::simd8x64& in, const json_block& block) { uint64_t mask = block.whitespace(); - dst += in.compress(mask, dst); + if (simdjson_unlikely(mask == 0)) { + in.store(dst); + dst += 64; + } else { + dst += in.compress(mask, dst); + } } simdjson_warn_unused simdjson_inline error_code json_minifier::finish(uint8_t *dst_start, size_t &dst_len) { @@ -19730,8 +20023,16 @@ simdjson_inline void json_minifier::step<128>(const uint8_t *block_buf, buf_bloc simd::simd8x64 in_2(block_buf+64); json_block block_1 = scanner.next(in_1); json_block block_2 = scanner.next(in_2); - this->next(in_1, block_1); - this->next(in_2, block_2); + const uint64_t mask_1 = block_1.whitespace(); + const uint64_t mask_2 = block_2.whitespace(); + if (simdjson_unlikely((mask_1 | mask_2) == 0)) { + in_1.store(dst); + in_2.store(dst + 64); + dst += 128; + } else { + dst += in_1.compress(mask_1, dst); + dst += in_2.compress(mask_2, dst); + } reader.advance(); } @@ -19754,12 +20055,12 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s } // Index the last (remainder) block, padded with spaces - uint8_t block[STEP_SIZE]; - size_t remaining_bytes = reader.get_remainder(block); + simdjson_indeterminate uint8_t block[STEP_SIZE]; + size_t remaining_bytes = reader.get_remainder_unpadded(block); if (remaining_bytes > 0) { // We do not want to write directly to the output stream. Rather, we write // to a local buffer (for safety). - uint8_t out_block[STEP_SIZE]; + simdjson_indeterminate uint8_t out_block[STEP_SIZE]; uint8_t * const guarded_dst{minifier.dst}; minifier.dst = out_block; minifier.step(block, reader); @@ -19809,8 +20110,8 @@ bool generic_validate_utf8(const uint8_t * input, size_t length) { c.check_next_input(in); reader.advance(); } - uint8_t block[64]{}; - reader.get_remainder(block); + uint8_t block[64]; + reader.get_remainder_unpadded(block); simd::simd8x64 in(block); c.check_next_input(in); reader.advance(); @@ -19971,6 +20272,8 @@ class json_structural_indexer { static error_code index(const uint8_t *buf, size_t len, dom_parser_implementation &parser, stage1_mode partial) noexcept; private: + template + static error_code index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept; simdjson_inline json_structural_indexer(uint32_t *structural_indexes); template simdjson_inline void step(const uint8_t *block, buf_block_reader &reader) noexcept; @@ -20029,6 +20332,15 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa if (simdjson_unlikely(len > parser.capacity())) { return CAPACITY; } // We guard the rest of the code so that we can assume that len > 0 throughout. if (len == 0) { return EMPTY; } + // Lone atoms only on a complete (non-streaming) buffer. Streaming windows + // have different truncation and partial-scalar rules. + if (partial == stage1_mode::regular && len <= 64 && buf[0] != '{' && buf[0] != '[' && buf[0] != '"') { + error_code atom = simdjson::internal::try_stage1_lone_atom(parser, buf, len); + if (atom != UNINITIALIZED) { return atom; } + } + if (partial == stage1_mode::regular && !parser._unpadded && len <= 128) { + return len <= 64 ? index_small<1>(buf, len, parser) : index_small<2>(buf, len, parser); + } if (is_streaming(partial)) { len = trim_partial_utf8(buf, len); // If you end up with an empty window after trimming @@ -20045,13 +20357,56 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa } // Take care of the last block (will always be there unless file is empty which is // not supposed to happen.) - uint8_t block[STEP_SIZE]; + simdjson_indeterminate uint8_t block[STEP_SIZE]; const size_t remaining = parser._unpadded ? reader.get_remainder(block) : reader.get_remainder_padded(block); if (simdjson_unlikely(remaining == 0)) { return UNEXPECTED_ERROR; } indexer.step(block, reader); return indexer.finish(parser, reader.block_index(), len, partial); } +// The error of a document that has an unclosed string, in regular mode. +simdjson_never_inline error_code unclosed_string_error(const uint8_t *buf, size_t len, bool unescaped_chars, bool utf8_suspect) noexcept { + if (unescaped_chars) { return UNESCAPED_CHARS; } + if (utf8_suspect && !generic_validate_utf8(buf, trim_partial_utf8(buf, len))) { return UTF8_ERROR; } + return UNCLOSED_STRING; +} + +// A document of at most 64 * BLOCKS bytes followed by SIMDJSON_PADDING bytes. +// Same result as the block loop and finish() in regular mode. +template +simdjson_inline error_code json_structural_indexer::index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept { + json_structural_indexer indexer(parser.structural_indexes.get()); + alignas(64) uint8_t block[64 * BLOCKS]; + buf_block_reader<64 * BLOCKS> reader(buf, len); + reader.get_remainder_padded(block); + simd::simd8x64 in_1(block); + json_block block_1 = indexer.scanner.next(in_1); + SIMDJSON_IF_CONSTEXPR (BLOCKS == 1) { + indexer.next(in_1, block_1, 0); + } else { + simd::simd8x64 in_2(block + 64); + json_block block_2 = indexer.scanner.next(in_2); + indexer.next(in_1, block_1, 0); + indexer.next(in_2, block_2, 64); + } + indexer.indexer.write(uint32_t(64 * BLOCKS - 64), indexer.prev_structurals); + const error_code error = indexer.scanner.finish(); + const uint32_t n = uint32_t(indexer.indexer.tail - parser.structural_indexes.get()); + parser.n_structural_indexes = n; + parser.structural_indexes[n] = uint32_t(len); + parser.structural_indexes[n + 1] = uint32_t(len); + parser.structural_indexes[n + 2] = 0; + parser.next_structural_index = 0; + if (simdjson_unlikely(error != SUCCESS)) { + return unclosed_string_error(buf, len, indexer.unescaped_chars_error != 0, indexer.checker.errors() != SUCCESS); + } + if (indexer.unescaped_chars_error) { return UNESCAPED_CHARS; } + // The bytes past len are spaces: no index exceeds len, unlike in finish(). + if (simdjson_unlikely(n == 0)) { return EMPTY; } + indexer.checker.check_eof(); + return indexer.checker.errors(); +} + template<> simdjson_inline void json_structural_indexer::step<128>(const uint8_t *block, buf_block_reader<128> &reader) noexcept { simd::simd8x64 in_1(block); @@ -20157,8 +20512,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // will be the quote and we want to make sure to omit it. if(have_unclosed_string) { parser.n_structural_indexes--; - // a valid JSON file cannot have zero structural indexes - we should have found something - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } // We truncate the input to the end of the last complete document (or zero). const bool partial_scalar = !have_unclosed_string && ends_with_partial_scalar(parser, len); @@ -20255,7 +20611,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Comma-delimited: filter root-level commas, use comma positions for batch boundaries if(have_unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } uint32_t next_batch_start = uint32_t(len); auto new_structural_indexes = filter_comma_delimited(parser, len, false, next_batch_start); @@ -22227,6 +22585,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/haswell/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/haswell/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -22449,6 +22808,26 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + const __m128i lo = n >= 16 ? _mm_loadu_si128(reinterpret_cast(ptr)) : load_partial_16(ptr, n, begin, fill); + const __m128i hi = n > 16 ? load_partial_16(ptr + 16, n - 16, begin, fill) : _mm_set1_epi8(char(fill)); + return _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -23012,10 +23391,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -23063,8 +23438,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -23258,6 +23633,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -23849,6 +24225,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -23902,19 +24287,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -23922,7 +24325,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -24303,10 +24708,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -24353,10 +24756,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -24408,10 +24809,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -24453,10 +24852,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -25394,6 +25791,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/haswell/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/haswell/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -25616,6 +26014,26 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + const __m128i lo = n >= 16 ? _mm_loadu_si128(reinterpret_cast(ptr)) : load_partial_16(ptr, n, begin, fill); + const __m128i hi = n > 16 ? load_partial_16(ptr + 16, n - 16, begin, fill) : _mm_set1_epi8(char(fill)); + return _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -25982,6 +26400,14 @@ struct buf_block_reader { * with full-width stores that the loads can forward from. */ simdjson_inline size_t get_remainder_padded(uint8_t *dst) const; + /** + * Like get_remainder, but reads only the input bytes: no padding is needed. + * + * The block is put together in vector registers and written with + * full-width stores, so that the loads that read it back are forwarded from + * the stores (see get_remainder_padded). + */ + simdjson_inline size_t get_remainder_unpadded(uint8_t *dst) const; simdjson_inline void advance(); private: const uint8_t *buf; @@ -26046,6 +26472,25 @@ simdjson_inline size_t buf_block_reader::get_remainder_padded(uint8_t return remaining; } +template +simdjson_inline size_t buf_block_reader::get_remainder_unpadded(uint8_t *dst) const { + const size_t remaining = len - idx; + constexpr size_t width = sizeof(simd::simd8); + for (size_t off = 0; off < STEP_SIZE; off += width) { + if (off + width <= remaining) { + const simd::simd8 v = simd::simd8::load(buf + idx + off); + v.store(dst + off); + } else if (off < remaining) { + const simd::simd8 v = simd::simd8::load_partial(buf + idx + off, remaining - off, buf, 0x20); + v.store(dst + off); + } else { + const simd::simd8 v = simd::simd8::splat(0x20); + v.store(dst + off); + } + } + return remaining; +} + template simdjson_inline void buf_block_reader::advance() { idx += STEP_SIZE; @@ -26964,11 +27409,9 @@ simdjson_inline uint32_t find_next_document_index_json_sequence( // Phase 2: Determine batch boundaries based on RS positions if (is_final) { - // Final batch: all documents are complete (last one ends at EOF). - // In json_sequence mode, RS markers define document boundaries, so all - // remaining structurals form complete documents. Return them all directly. - // (Calling find_next_document_index() would fail for scalar documents.) - return parser.n_structural_indexes; + // A cut number must not be parsed into padding the caller does not + // initialize. Leave that record to truncated_bytes(), as streaming_final does. + return find_next_document_index(parser); } // Partial batch: need to find complete documents only. @@ -27087,9 +27530,13 @@ simdjson_inline uint32_t filter_comma_delimited( // A document ending with a root comma is complete. if (root_comma_count == 0) { // No root commas found; we cannot confirm any document is complete. - // The whole batch might be one incomplete document. - // Return DOCUMENT_TOO_LARGE if content was found (write_idx > 0), 0 if only commas. - return (parser.n_structural_indexes > 0) ? DOCUMENT_TOO_LARGE : 0; + // The whole batch might be one incomplete document. If white space comes + // before it, a batch that starts at the document may hold it. + if (parser.structural_indexes[0] > 0) { + next_batch_start = parser.structural_indexes[0]; + return 0; + } + return DOCUMENT_TOO_LARGE; } // We have at least one root comma. Documents before the last comma are complete. @@ -27158,7 +27605,12 @@ class json_minifier { simdjson_inline void json_minifier::next(const simd::simd8x64& in, const json_block& block) { uint64_t mask = block.whitespace(); - dst += in.compress(mask, dst); + if (simdjson_unlikely(mask == 0)) { + in.store(dst); + dst += 64; + } else { + dst += in.compress(mask, dst); + } } simdjson_warn_unused simdjson_inline error_code json_minifier::finish(uint8_t *dst_start, size_t &dst_len) { @@ -27174,8 +27626,16 @@ simdjson_inline void json_minifier::step<128>(const uint8_t *block_buf, buf_bloc simd::simd8x64 in_2(block_buf+64); json_block block_1 = scanner.next(in_1); json_block block_2 = scanner.next(in_2); - this->next(in_1, block_1); - this->next(in_2, block_2); + const uint64_t mask_1 = block_1.whitespace(); + const uint64_t mask_2 = block_2.whitespace(); + if (simdjson_unlikely((mask_1 | mask_2) == 0)) { + in_1.store(dst); + in_2.store(dst + 64); + dst += 128; + } else { + dst += in_1.compress(mask_1, dst); + dst += in_2.compress(mask_2, dst); + } reader.advance(); } @@ -27198,12 +27658,12 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s } // Index the last (remainder) block, padded with spaces - uint8_t block[STEP_SIZE]; - size_t remaining_bytes = reader.get_remainder(block); + simdjson_indeterminate uint8_t block[STEP_SIZE]; + size_t remaining_bytes = reader.get_remainder_unpadded(block); if (remaining_bytes > 0) { // We do not want to write directly to the output stream. Rather, we write // to a local buffer (for safety). - uint8_t out_block[STEP_SIZE]; + simdjson_indeterminate uint8_t out_block[STEP_SIZE]; uint8_t * const guarded_dst{minifier.dst}; minifier.dst = out_block; minifier.step(block, reader); @@ -27253,8 +27713,8 @@ bool generic_validate_utf8(const uint8_t * input, size_t length) { c.check_next_input(in); reader.advance(); } - uint8_t block[64]{}; - reader.get_remainder(block); + uint8_t block[64]; + reader.get_remainder_unpadded(block); simd::simd8x64 in(block); c.check_next_input(in); reader.advance(); @@ -27415,6 +27875,8 @@ class json_structural_indexer { static error_code index(const uint8_t *buf, size_t len, dom_parser_implementation &parser, stage1_mode partial) noexcept; private: + template + static error_code index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept; simdjson_inline json_structural_indexer(uint32_t *structural_indexes); template simdjson_inline void step(const uint8_t *block, buf_block_reader &reader) noexcept; @@ -27473,6 +27935,15 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa if (simdjson_unlikely(len > parser.capacity())) { return CAPACITY; } // We guard the rest of the code so that we can assume that len > 0 throughout. if (len == 0) { return EMPTY; } + // Lone atoms only on a complete (non-streaming) buffer. Streaming windows + // have different truncation and partial-scalar rules. + if (partial == stage1_mode::regular && len <= 64 && buf[0] != '{' && buf[0] != '[' && buf[0] != '"') { + error_code atom = simdjson::internal::try_stage1_lone_atom(parser, buf, len); + if (atom != UNINITIALIZED) { return atom; } + } + if (partial == stage1_mode::regular && !parser._unpadded && len <= 128) { + return len <= 64 ? index_small<1>(buf, len, parser) : index_small<2>(buf, len, parser); + } if (is_streaming(partial)) { len = trim_partial_utf8(buf, len); // If you end up with an empty window after trimming @@ -27489,13 +27960,56 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa } // Take care of the last block (will always be there unless file is empty which is // not supposed to happen.) - uint8_t block[STEP_SIZE]; + simdjson_indeterminate uint8_t block[STEP_SIZE]; const size_t remaining = parser._unpadded ? reader.get_remainder(block) : reader.get_remainder_padded(block); if (simdjson_unlikely(remaining == 0)) { return UNEXPECTED_ERROR; } indexer.step(block, reader); return indexer.finish(parser, reader.block_index(), len, partial); } +// The error of a document that has an unclosed string, in regular mode. +simdjson_never_inline error_code unclosed_string_error(const uint8_t *buf, size_t len, bool unescaped_chars, bool utf8_suspect) noexcept { + if (unescaped_chars) { return UNESCAPED_CHARS; } + if (utf8_suspect && !generic_validate_utf8(buf, trim_partial_utf8(buf, len))) { return UTF8_ERROR; } + return UNCLOSED_STRING; +} + +// A document of at most 64 * BLOCKS bytes followed by SIMDJSON_PADDING bytes. +// Same result as the block loop and finish() in regular mode. +template +simdjson_inline error_code json_structural_indexer::index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept { + json_structural_indexer indexer(parser.structural_indexes.get()); + alignas(64) uint8_t block[64 * BLOCKS]; + buf_block_reader<64 * BLOCKS> reader(buf, len); + reader.get_remainder_padded(block); + simd::simd8x64 in_1(block); + json_block block_1 = indexer.scanner.next(in_1); + SIMDJSON_IF_CONSTEXPR (BLOCKS == 1) { + indexer.next(in_1, block_1, 0); + } else { + simd::simd8x64 in_2(block + 64); + json_block block_2 = indexer.scanner.next(in_2); + indexer.next(in_1, block_1, 0); + indexer.next(in_2, block_2, 64); + } + indexer.indexer.write(uint32_t(64 * BLOCKS - 64), indexer.prev_structurals); + const error_code error = indexer.scanner.finish(); + const uint32_t n = uint32_t(indexer.indexer.tail - parser.structural_indexes.get()); + parser.n_structural_indexes = n; + parser.structural_indexes[n] = uint32_t(len); + parser.structural_indexes[n + 1] = uint32_t(len); + parser.structural_indexes[n + 2] = 0; + parser.next_structural_index = 0; + if (simdjson_unlikely(error != SUCCESS)) { + return unclosed_string_error(buf, len, indexer.unescaped_chars_error != 0, indexer.checker.errors() != SUCCESS); + } + if (indexer.unescaped_chars_error) { return UNESCAPED_CHARS; } + // The bytes past len are spaces: no index exceeds len, unlike in finish(). + if (simdjson_unlikely(n == 0)) { return EMPTY; } + indexer.checker.check_eof(); + return indexer.checker.errors(); +} + template<> simdjson_inline void json_structural_indexer::step<128>(const uint8_t *block, buf_block_reader<128> &reader) noexcept { simd::simd8x64 in_1(block); @@ -27601,8 +28115,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // will be the quote and we want to make sure to omit it. if(have_unclosed_string) { parser.n_structural_indexes--; - // a valid JSON file cannot have zero structural indexes - we should have found something - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } // We truncate the input to the end of the last complete document (or zero). const bool partial_scalar = !have_unclosed_string && ends_with_partial_scalar(parser, len); @@ -27699,7 +28214,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Comma-delimited: filter root-level commas, use comma positions for batch boundaries if(have_unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } uint32_t next_batch_start = uint32_t(len); auto new_structural_indexes = filter_comma_delimited(parser, len, false, next_batch_start); @@ -29812,6 +30329,12 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 64 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + // Masked-off bytes are not read, so they cannot fault. + return _mm512_mask_loadu_epi8(_mm512_set1_epi8(char(fill)), (uint64_t(1) << n) - 1, ptr); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m512i _value) : base8_numeric(_value) {} // Splat constructor @@ -30432,10 +30955,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -30483,8 +31002,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -30678,6 +31197,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -31269,6 +31789,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -31322,19 +31851,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -31342,7 +31889,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -31723,10 +32272,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -31773,10 +32320,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -31828,10 +32373,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -31873,10 +32416,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -32974,6 +33515,12 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 64 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + // Masked-off bytes are not read, so they cannot fault. + return _mm512_mask_loadu_epi8(_mm512_set1_epi8(char(fill)), (uint64_t(1) << n) - 1, ptr); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m512i _value) : base8_numeric(_value) {} // Splat constructor @@ -33397,6 +33944,14 @@ struct buf_block_reader { * with full-width stores that the loads can forward from. */ simdjson_inline size_t get_remainder_padded(uint8_t *dst) const; + /** + * Like get_remainder, but reads only the input bytes: no padding is needed. + * + * The block is put together in vector registers and written with + * full-width stores, so that the loads that read it back are forwarded from + * the stores (see get_remainder_padded). + */ + simdjson_inline size_t get_remainder_unpadded(uint8_t *dst) const; simdjson_inline void advance(); private: const uint8_t *buf; @@ -33461,6 +34016,25 @@ simdjson_inline size_t buf_block_reader::get_remainder_padded(uint8_t return remaining; } +template +simdjson_inline size_t buf_block_reader::get_remainder_unpadded(uint8_t *dst) const { + const size_t remaining = len - idx; + constexpr size_t width = sizeof(simd::simd8); + for (size_t off = 0; off < STEP_SIZE; off += width) { + if (off + width <= remaining) { + const simd::simd8 v = simd::simd8::load(buf + idx + off); + v.store(dst + off); + } else if (off < remaining) { + const simd::simd8 v = simd::simd8::load_partial(buf + idx + off, remaining - off, buf, 0x20); + v.store(dst + off); + } else { + const simd::simd8 v = simd::simd8::splat(0x20); + v.store(dst + off); + } + } + return remaining; +} + template simdjson_inline void buf_block_reader::advance() { idx += STEP_SIZE; @@ -34379,11 +34953,9 @@ simdjson_inline uint32_t find_next_document_index_json_sequence( // Phase 2: Determine batch boundaries based on RS positions if (is_final) { - // Final batch: all documents are complete (last one ends at EOF). - // In json_sequence mode, RS markers define document boundaries, so all - // remaining structurals form complete documents. Return them all directly. - // (Calling find_next_document_index() would fail for scalar documents.) - return parser.n_structural_indexes; + // A cut number must not be parsed into padding the caller does not + // initialize. Leave that record to truncated_bytes(), as streaming_final does. + return find_next_document_index(parser); } // Partial batch: need to find complete documents only. @@ -34502,9 +35074,13 @@ simdjson_inline uint32_t filter_comma_delimited( // A document ending with a root comma is complete. if (root_comma_count == 0) { // No root commas found; we cannot confirm any document is complete. - // The whole batch might be one incomplete document. - // Return DOCUMENT_TOO_LARGE if content was found (write_idx > 0), 0 if only commas. - return (parser.n_structural_indexes > 0) ? DOCUMENT_TOO_LARGE : 0; + // The whole batch might be one incomplete document. If white space comes + // before it, a batch that starts at the document may hold it. + if (parser.structural_indexes[0] > 0) { + next_batch_start = parser.structural_indexes[0]; + return 0; + } + return DOCUMENT_TOO_LARGE; } // We have at least one root comma. Documents before the last comma are complete. @@ -34573,7 +35149,12 @@ class json_minifier { simdjson_inline void json_minifier::next(const simd::simd8x64& in, const json_block& block) { uint64_t mask = block.whitespace(); - dst += in.compress(mask, dst); + if (simdjson_unlikely(mask == 0)) { + in.store(dst); + dst += 64; + } else { + dst += in.compress(mask, dst); + } } simdjson_warn_unused simdjson_inline error_code json_minifier::finish(uint8_t *dst_start, size_t &dst_len) { @@ -34589,8 +35170,16 @@ simdjson_inline void json_minifier::step<128>(const uint8_t *block_buf, buf_bloc simd::simd8x64 in_2(block_buf+64); json_block block_1 = scanner.next(in_1); json_block block_2 = scanner.next(in_2); - this->next(in_1, block_1); - this->next(in_2, block_2); + const uint64_t mask_1 = block_1.whitespace(); + const uint64_t mask_2 = block_2.whitespace(); + if (simdjson_unlikely((mask_1 | mask_2) == 0)) { + in_1.store(dst); + in_2.store(dst + 64); + dst += 128; + } else { + dst += in_1.compress(mask_1, dst); + dst += in_2.compress(mask_2, dst); + } reader.advance(); } @@ -34613,12 +35202,12 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s } // Index the last (remainder) block, padded with spaces - uint8_t block[STEP_SIZE]; - size_t remaining_bytes = reader.get_remainder(block); + simdjson_indeterminate uint8_t block[STEP_SIZE]; + size_t remaining_bytes = reader.get_remainder_unpadded(block); if (remaining_bytes > 0) { // We do not want to write directly to the output stream. Rather, we write // to a local buffer (for safety). - uint8_t out_block[STEP_SIZE]; + simdjson_indeterminate uint8_t out_block[STEP_SIZE]; uint8_t * const guarded_dst{minifier.dst}; minifier.dst = out_block; minifier.step(block, reader); @@ -34668,8 +35257,8 @@ bool generic_validate_utf8(const uint8_t * input, size_t length) { c.check_next_input(in); reader.advance(); } - uint8_t block[64]{}; - reader.get_remainder(block); + uint8_t block[64]; + reader.get_remainder_unpadded(block); simd::simd8x64 in(block); c.check_next_input(in); reader.advance(); @@ -34830,6 +35419,8 @@ class json_structural_indexer { static error_code index(const uint8_t *buf, size_t len, dom_parser_implementation &parser, stage1_mode partial) noexcept; private: + template + static error_code index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept; simdjson_inline json_structural_indexer(uint32_t *structural_indexes); template simdjson_inline void step(const uint8_t *block, buf_block_reader &reader) noexcept; @@ -34888,6 +35479,15 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa if (simdjson_unlikely(len > parser.capacity())) { return CAPACITY; } // We guard the rest of the code so that we can assume that len > 0 throughout. if (len == 0) { return EMPTY; } + // Lone atoms only on a complete (non-streaming) buffer. Streaming windows + // have different truncation and partial-scalar rules. + if (partial == stage1_mode::regular && len <= 64 && buf[0] != '{' && buf[0] != '[' && buf[0] != '"') { + error_code atom = simdjson::internal::try_stage1_lone_atom(parser, buf, len); + if (atom != UNINITIALIZED) { return atom; } + } + if (partial == stage1_mode::regular && !parser._unpadded && len <= 128) { + return len <= 64 ? index_small<1>(buf, len, parser) : index_small<2>(buf, len, parser); + } if (is_streaming(partial)) { len = trim_partial_utf8(buf, len); // If you end up with an empty window after trimming @@ -34904,13 +35504,56 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa } // Take care of the last block (will always be there unless file is empty which is // not supposed to happen.) - uint8_t block[STEP_SIZE]; + simdjson_indeterminate uint8_t block[STEP_SIZE]; const size_t remaining = parser._unpadded ? reader.get_remainder(block) : reader.get_remainder_padded(block); if (simdjson_unlikely(remaining == 0)) { return UNEXPECTED_ERROR; } indexer.step(block, reader); return indexer.finish(parser, reader.block_index(), len, partial); } +// The error of a document that has an unclosed string, in regular mode. +simdjson_never_inline error_code unclosed_string_error(const uint8_t *buf, size_t len, bool unescaped_chars, bool utf8_suspect) noexcept { + if (unescaped_chars) { return UNESCAPED_CHARS; } + if (utf8_suspect && !generic_validate_utf8(buf, trim_partial_utf8(buf, len))) { return UTF8_ERROR; } + return UNCLOSED_STRING; +} + +// A document of at most 64 * BLOCKS bytes followed by SIMDJSON_PADDING bytes. +// Same result as the block loop and finish() in regular mode. +template +simdjson_inline error_code json_structural_indexer::index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept { + json_structural_indexer indexer(parser.structural_indexes.get()); + alignas(64) uint8_t block[64 * BLOCKS]; + buf_block_reader<64 * BLOCKS> reader(buf, len); + reader.get_remainder_padded(block); + simd::simd8x64 in_1(block); + json_block block_1 = indexer.scanner.next(in_1); + SIMDJSON_IF_CONSTEXPR (BLOCKS == 1) { + indexer.next(in_1, block_1, 0); + } else { + simd::simd8x64 in_2(block + 64); + json_block block_2 = indexer.scanner.next(in_2); + indexer.next(in_1, block_1, 0); + indexer.next(in_2, block_2, 64); + } + indexer.indexer.write(uint32_t(64 * BLOCKS - 64), indexer.prev_structurals); + const error_code error = indexer.scanner.finish(); + const uint32_t n = uint32_t(indexer.indexer.tail - parser.structural_indexes.get()); + parser.n_structural_indexes = n; + parser.structural_indexes[n] = uint32_t(len); + parser.structural_indexes[n + 1] = uint32_t(len); + parser.structural_indexes[n + 2] = 0; + parser.next_structural_index = 0; + if (simdjson_unlikely(error != SUCCESS)) { + return unclosed_string_error(buf, len, indexer.unescaped_chars_error != 0, indexer.checker.errors() != SUCCESS); + } + if (indexer.unescaped_chars_error) { return UNESCAPED_CHARS; } + // The bytes past len are spaces: no index exceeds len, unlike in finish(). + if (simdjson_unlikely(n == 0)) { return EMPTY; } + indexer.checker.check_eof(); + return indexer.checker.errors(); +} + template<> simdjson_inline void json_structural_indexer::step<128>(const uint8_t *block, buf_block_reader<128> &reader) noexcept { simd::simd8x64 in_1(block); @@ -35016,8 +35659,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // will be the quote and we want to make sure to omit it. if(have_unclosed_string) { parser.n_structural_indexes--; - // a valid JSON file cannot have zero structural indexes - we should have found something - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } // We truncate the input to the end of the last complete document (or zero). const bool partial_scalar = !have_unclosed_string && ends_with_partial_scalar(parser, len); @@ -35114,7 +35758,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Comma-delimited: filter root-level commas, use comma positions for batch boundaries if(have_unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } uint32_t next_batch_start = uint32_t(len); auto new_structural_indexes = filter_comma_delimited(parser, len, false, next_batch_start); @@ -37029,6 +37675,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/ppc64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/ppc64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -37044,7 +37691,6 @@ namespace ppc64 { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; @@ -37056,9 +37702,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars val = bswap64(val); #endif #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -37384,6 +38028,14 @@ template <> struct simd8 : base8_numeric { // Unsigned bytes template <> struct simd8 : base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} @@ -38011,10 +38663,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -38062,8 +38710,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -38257,6 +38905,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -38848,6 +39497,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -38901,19 +39559,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -38921,7 +39597,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -39302,10 +39980,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -39352,10 +40028,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -39407,10 +40081,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -39452,10 +40124,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -40310,6 +40980,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/ppc64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/ppc64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -40325,7 +40996,6 @@ namespace ppc64 { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; @@ -40337,9 +41007,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars val = bswap64(val); #endif #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -40665,6 +41333,14 @@ template <> struct simd8 : base8_numeric { // Unsigned bytes template <> struct simd8 : base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} @@ -41095,6 +41771,14 @@ struct buf_block_reader { * with full-width stores that the loads can forward from. */ simdjson_inline size_t get_remainder_padded(uint8_t *dst) const; + /** + * Like get_remainder, but reads only the input bytes: no padding is needed. + * + * The block is put together in vector registers and written with + * full-width stores, so that the loads that read it back are forwarded from + * the stores (see get_remainder_padded). + */ + simdjson_inline size_t get_remainder_unpadded(uint8_t *dst) const; simdjson_inline void advance(); private: const uint8_t *buf; @@ -41159,6 +41843,25 @@ simdjson_inline size_t buf_block_reader::get_remainder_padded(uint8_t return remaining; } +template +simdjson_inline size_t buf_block_reader::get_remainder_unpadded(uint8_t *dst) const { + const size_t remaining = len - idx; + constexpr size_t width = sizeof(simd::simd8); + for (size_t off = 0; off < STEP_SIZE; off += width) { + if (off + width <= remaining) { + const simd::simd8 v = simd::simd8::load(buf + idx + off); + v.store(dst + off); + } else if (off < remaining) { + const simd::simd8 v = simd::simd8::load_partial(buf + idx + off, remaining - off, buf, 0x20); + v.store(dst + off); + } else { + const simd::simd8 v = simd::simd8::splat(0x20); + v.store(dst + off); + } + } + return remaining; +} + template simdjson_inline void buf_block_reader::advance() { idx += STEP_SIZE; @@ -42077,11 +42780,9 @@ simdjson_inline uint32_t find_next_document_index_json_sequence( // Phase 2: Determine batch boundaries based on RS positions if (is_final) { - // Final batch: all documents are complete (last one ends at EOF). - // In json_sequence mode, RS markers define document boundaries, so all - // remaining structurals form complete documents. Return them all directly. - // (Calling find_next_document_index() would fail for scalar documents.) - return parser.n_structural_indexes; + // A cut number must not be parsed into padding the caller does not + // initialize. Leave that record to truncated_bytes(), as streaming_final does. + return find_next_document_index(parser); } // Partial batch: need to find complete documents only. @@ -42200,9 +42901,13 @@ simdjson_inline uint32_t filter_comma_delimited( // A document ending with a root comma is complete. if (root_comma_count == 0) { // No root commas found; we cannot confirm any document is complete. - // The whole batch might be one incomplete document. - // Return DOCUMENT_TOO_LARGE if content was found (write_idx > 0), 0 if only commas. - return (parser.n_structural_indexes > 0) ? DOCUMENT_TOO_LARGE : 0; + // The whole batch might be one incomplete document. If white space comes + // before it, a batch that starts at the document may hold it. + if (parser.structural_indexes[0] > 0) { + next_batch_start = parser.structural_indexes[0]; + return 0; + } + return DOCUMENT_TOO_LARGE; } // We have at least one root comma. Documents before the last comma are complete. @@ -42271,7 +42976,12 @@ class json_minifier { simdjson_inline void json_minifier::next(const simd::simd8x64& in, const json_block& block) { uint64_t mask = block.whitespace(); - dst += in.compress(mask, dst); + if (simdjson_unlikely(mask == 0)) { + in.store(dst); + dst += 64; + } else { + dst += in.compress(mask, dst); + } } simdjson_warn_unused simdjson_inline error_code json_minifier::finish(uint8_t *dst_start, size_t &dst_len) { @@ -42287,8 +42997,16 @@ simdjson_inline void json_minifier::step<128>(const uint8_t *block_buf, buf_bloc simd::simd8x64 in_2(block_buf+64); json_block block_1 = scanner.next(in_1); json_block block_2 = scanner.next(in_2); - this->next(in_1, block_1); - this->next(in_2, block_2); + const uint64_t mask_1 = block_1.whitespace(); + const uint64_t mask_2 = block_2.whitespace(); + if (simdjson_unlikely((mask_1 | mask_2) == 0)) { + in_1.store(dst); + in_2.store(dst + 64); + dst += 128; + } else { + dst += in_1.compress(mask_1, dst); + dst += in_2.compress(mask_2, dst); + } reader.advance(); } @@ -42311,12 +43029,12 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s } // Index the last (remainder) block, padded with spaces - uint8_t block[STEP_SIZE]; - size_t remaining_bytes = reader.get_remainder(block); + simdjson_indeterminate uint8_t block[STEP_SIZE]; + size_t remaining_bytes = reader.get_remainder_unpadded(block); if (remaining_bytes > 0) { // We do not want to write directly to the output stream. Rather, we write // to a local buffer (for safety). - uint8_t out_block[STEP_SIZE]; + simdjson_indeterminate uint8_t out_block[STEP_SIZE]; uint8_t * const guarded_dst{minifier.dst}; minifier.dst = out_block; minifier.step(block, reader); @@ -42366,8 +43084,8 @@ bool generic_validate_utf8(const uint8_t * input, size_t length) { c.check_next_input(in); reader.advance(); } - uint8_t block[64]{}; - reader.get_remainder(block); + uint8_t block[64]; + reader.get_remainder_unpadded(block); simd::simd8x64 in(block); c.check_next_input(in); reader.advance(); @@ -42528,6 +43246,8 @@ class json_structural_indexer { static error_code index(const uint8_t *buf, size_t len, dom_parser_implementation &parser, stage1_mode partial) noexcept; private: + template + static error_code index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept; simdjson_inline json_structural_indexer(uint32_t *structural_indexes); template simdjson_inline void step(const uint8_t *block, buf_block_reader &reader) noexcept; @@ -42586,6 +43306,15 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa if (simdjson_unlikely(len > parser.capacity())) { return CAPACITY; } // We guard the rest of the code so that we can assume that len > 0 throughout. if (len == 0) { return EMPTY; } + // Lone atoms only on a complete (non-streaming) buffer. Streaming windows + // have different truncation and partial-scalar rules. + if (partial == stage1_mode::regular && len <= 64 && buf[0] != '{' && buf[0] != '[' && buf[0] != '"') { + error_code atom = simdjson::internal::try_stage1_lone_atom(parser, buf, len); + if (atom != UNINITIALIZED) { return atom; } + } + if (partial == stage1_mode::regular && !parser._unpadded && len <= 128) { + return len <= 64 ? index_small<1>(buf, len, parser) : index_small<2>(buf, len, parser); + } if (is_streaming(partial)) { len = trim_partial_utf8(buf, len); // If you end up with an empty window after trimming @@ -42602,13 +43331,56 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa } // Take care of the last block (will always be there unless file is empty which is // not supposed to happen.) - uint8_t block[STEP_SIZE]; + simdjson_indeterminate uint8_t block[STEP_SIZE]; const size_t remaining = parser._unpadded ? reader.get_remainder(block) : reader.get_remainder_padded(block); if (simdjson_unlikely(remaining == 0)) { return UNEXPECTED_ERROR; } indexer.step(block, reader); return indexer.finish(parser, reader.block_index(), len, partial); } +// The error of a document that has an unclosed string, in regular mode. +simdjson_never_inline error_code unclosed_string_error(const uint8_t *buf, size_t len, bool unescaped_chars, bool utf8_suspect) noexcept { + if (unescaped_chars) { return UNESCAPED_CHARS; } + if (utf8_suspect && !generic_validate_utf8(buf, trim_partial_utf8(buf, len))) { return UTF8_ERROR; } + return UNCLOSED_STRING; +} + +// A document of at most 64 * BLOCKS bytes followed by SIMDJSON_PADDING bytes. +// Same result as the block loop and finish() in regular mode. +template +simdjson_inline error_code json_structural_indexer::index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept { + json_structural_indexer indexer(parser.structural_indexes.get()); + alignas(64) uint8_t block[64 * BLOCKS]; + buf_block_reader<64 * BLOCKS> reader(buf, len); + reader.get_remainder_padded(block); + simd::simd8x64 in_1(block); + json_block block_1 = indexer.scanner.next(in_1); + SIMDJSON_IF_CONSTEXPR (BLOCKS == 1) { + indexer.next(in_1, block_1, 0); + } else { + simd::simd8x64 in_2(block + 64); + json_block block_2 = indexer.scanner.next(in_2); + indexer.next(in_1, block_1, 0); + indexer.next(in_2, block_2, 64); + } + indexer.indexer.write(uint32_t(64 * BLOCKS - 64), indexer.prev_structurals); + const error_code error = indexer.scanner.finish(); + const uint32_t n = uint32_t(indexer.indexer.tail - parser.structural_indexes.get()); + parser.n_structural_indexes = n; + parser.structural_indexes[n] = uint32_t(len); + parser.structural_indexes[n + 1] = uint32_t(len); + parser.structural_indexes[n + 2] = 0; + parser.next_structural_index = 0; + if (simdjson_unlikely(error != SUCCESS)) { + return unclosed_string_error(buf, len, indexer.unescaped_chars_error != 0, indexer.checker.errors() != SUCCESS); + } + if (indexer.unescaped_chars_error) { return UNESCAPED_CHARS; } + // The bytes past len are spaces: no index exceeds len, unlike in finish(). + if (simdjson_unlikely(n == 0)) { return EMPTY; } + indexer.checker.check_eof(); + return indexer.checker.errors(); +} + template<> simdjson_inline void json_structural_indexer::step<128>(const uint8_t *block, buf_block_reader<128> &reader) noexcept { simd::simd8x64 in_1(block); @@ -42714,8 +43486,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // will be the quote and we want to make sure to omit it. if(have_unclosed_string) { parser.n_structural_indexes--; - // a valid JSON file cannot have zero structural indexes - we should have found something - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } // We truncate the input to the end of the last complete document (or zero). const bool partial_scalar = !have_unclosed_string && ends_with_partial_scalar(parser, len); @@ -42812,7 +43585,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Comma-delimited: filter root-level commas, use comma positions for batch boundaries if(have_unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } uint32_t next_batch_start = uint32_t(len); auto new_structural_indexes = filter_comma_delimited(parser, len, false, next_batch_start); @@ -44781,6 +45556,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -44975,6 +45751,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -45200,6 +45994,7 @@ simdjson_inline long long int count_ones(uint64_t input_num) { /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -45394,6 +46189,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -45944,10 +46757,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -45995,8 +46804,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -46190,6 +46999,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -46781,6 +47591,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -46834,19 +47653,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -46854,7 +47691,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -47235,10 +48074,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -47285,10 +48122,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -47340,10 +48175,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -47385,10 +48218,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -48365,6 +49196,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -48559,6 +49391,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -48784,6 +49634,7 @@ simdjson_inline long long int count_ones(uint64_t input_num) { /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -48978,6 +49829,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -49331,6 +50200,14 @@ struct buf_block_reader { * with full-width stores that the loads can forward from. */ simdjson_inline size_t get_remainder_padded(uint8_t *dst) const; + /** + * Like get_remainder, but reads only the input bytes: no padding is needed. + * + * The block is put together in vector registers and written with + * full-width stores, so that the loads that read it back are forwarded from + * the stores (see get_remainder_padded). + */ + simdjson_inline size_t get_remainder_unpadded(uint8_t *dst) const; simdjson_inline void advance(); private: const uint8_t *buf; @@ -49395,6 +50272,25 @@ simdjson_inline size_t buf_block_reader::get_remainder_padded(uint8_t return remaining; } +template +simdjson_inline size_t buf_block_reader::get_remainder_unpadded(uint8_t *dst) const { + const size_t remaining = len - idx; + constexpr size_t width = sizeof(simd::simd8); + for (size_t off = 0; off < STEP_SIZE; off += width) { + if (off + width <= remaining) { + const simd::simd8 v = simd::simd8::load(buf + idx + off); + v.store(dst + off); + } else if (off < remaining) { + const simd::simd8 v = simd::simd8::load_partial(buf + idx + off, remaining - off, buf, 0x20); + v.store(dst + off); + } else { + const simd::simd8 v = simd::simd8::splat(0x20); + v.store(dst + off); + } + } + return remaining; +} + template simdjson_inline void buf_block_reader::advance() { idx += STEP_SIZE; @@ -50313,11 +51209,9 @@ simdjson_inline uint32_t find_next_document_index_json_sequence( // Phase 2: Determine batch boundaries based on RS positions if (is_final) { - // Final batch: all documents are complete (last one ends at EOF). - // In json_sequence mode, RS markers define document boundaries, so all - // remaining structurals form complete documents. Return them all directly. - // (Calling find_next_document_index() would fail for scalar documents.) - return parser.n_structural_indexes; + // A cut number must not be parsed into padding the caller does not + // initialize. Leave that record to truncated_bytes(), as streaming_final does. + return find_next_document_index(parser); } // Partial batch: need to find complete documents only. @@ -50436,9 +51330,13 @@ simdjson_inline uint32_t filter_comma_delimited( // A document ending with a root comma is complete. if (root_comma_count == 0) { // No root commas found; we cannot confirm any document is complete. - // The whole batch might be one incomplete document. - // Return DOCUMENT_TOO_LARGE if content was found (write_idx > 0), 0 if only commas. - return (parser.n_structural_indexes > 0) ? DOCUMENT_TOO_LARGE : 0; + // The whole batch might be one incomplete document. If white space comes + // before it, a batch that starts at the document may hold it. + if (parser.structural_indexes[0] > 0) { + next_batch_start = parser.structural_indexes[0]; + return 0; + } + return DOCUMENT_TOO_LARGE; } // We have at least one root comma. Documents before the last comma are complete. @@ -50507,7 +51405,12 @@ class json_minifier { simdjson_inline void json_minifier::next(const simd::simd8x64& in, const json_block& block) { uint64_t mask = block.whitespace(); - dst += in.compress(mask, dst); + if (simdjson_unlikely(mask == 0)) { + in.store(dst); + dst += 64; + } else { + dst += in.compress(mask, dst); + } } simdjson_warn_unused simdjson_inline error_code json_minifier::finish(uint8_t *dst_start, size_t &dst_len) { @@ -50523,8 +51426,16 @@ simdjson_inline void json_minifier::step<128>(const uint8_t *block_buf, buf_bloc simd::simd8x64 in_2(block_buf+64); json_block block_1 = scanner.next(in_1); json_block block_2 = scanner.next(in_2); - this->next(in_1, block_1); - this->next(in_2, block_2); + const uint64_t mask_1 = block_1.whitespace(); + const uint64_t mask_2 = block_2.whitespace(); + if (simdjson_unlikely((mask_1 | mask_2) == 0)) { + in_1.store(dst); + in_2.store(dst + 64); + dst += 128; + } else { + dst += in_1.compress(mask_1, dst); + dst += in_2.compress(mask_2, dst); + } reader.advance(); } @@ -50547,12 +51458,12 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s } // Index the last (remainder) block, padded with spaces - uint8_t block[STEP_SIZE]; - size_t remaining_bytes = reader.get_remainder(block); + simdjson_indeterminate uint8_t block[STEP_SIZE]; + size_t remaining_bytes = reader.get_remainder_unpadded(block); if (remaining_bytes > 0) { // We do not want to write directly to the output stream. Rather, we write // to a local buffer (for safety). - uint8_t out_block[STEP_SIZE]; + simdjson_indeterminate uint8_t out_block[STEP_SIZE]; uint8_t * const guarded_dst{minifier.dst}; minifier.dst = out_block; minifier.step(block, reader); @@ -50602,8 +51513,8 @@ bool generic_validate_utf8(const uint8_t * input, size_t length) { c.check_next_input(in); reader.advance(); } - uint8_t block[64]{}; - reader.get_remainder(block); + uint8_t block[64]; + reader.get_remainder_unpadded(block); simd::simd8x64 in(block); c.check_next_input(in); reader.advance(); @@ -50764,6 +51675,8 @@ class json_structural_indexer { static error_code index(const uint8_t *buf, size_t len, dom_parser_implementation &parser, stage1_mode partial) noexcept; private: + template + static error_code index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept; simdjson_inline json_structural_indexer(uint32_t *structural_indexes); template simdjson_inline void step(const uint8_t *block, buf_block_reader &reader) noexcept; @@ -50822,6 +51735,15 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa if (simdjson_unlikely(len > parser.capacity())) { return CAPACITY; } // We guard the rest of the code so that we can assume that len > 0 throughout. if (len == 0) { return EMPTY; } + // Lone atoms only on a complete (non-streaming) buffer. Streaming windows + // have different truncation and partial-scalar rules. + if (partial == stage1_mode::regular && len <= 64 && buf[0] != '{' && buf[0] != '[' && buf[0] != '"') { + error_code atom = simdjson::internal::try_stage1_lone_atom(parser, buf, len); + if (atom != UNINITIALIZED) { return atom; } + } + if (partial == stage1_mode::regular && !parser._unpadded && len <= 128) { + return len <= 64 ? index_small<1>(buf, len, parser) : index_small<2>(buf, len, parser); + } if (is_streaming(partial)) { len = trim_partial_utf8(buf, len); // If you end up with an empty window after trimming @@ -50838,13 +51760,56 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa } // Take care of the last block (will always be there unless file is empty which is // not supposed to happen.) - uint8_t block[STEP_SIZE]; + simdjson_indeterminate uint8_t block[STEP_SIZE]; const size_t remaining = parser._unpadded ? reader.get_remainder(block) : reader.get_remainder_padded(block); if (simdjson_unlikely(remaining == 0)) { return UNEXPECTED_ERROR; } indexer.step(block, reader); return indexer.finish(parser, reader.block_index(), len, partial); } +// The error of a document that has an unclosed string, in regular mode. +simdjson_never_inline error_code unclosed_string_error(const uint8_t *buf, size_t len, bool unescaped_chars, bool utf8_suspect) noexcept { + if (unescaped_chars) { return UNESCAPED_CHARS; } + if (utf8_suspect && !generic_validate_utf8(buf, trim_partial_utf8(buf, len))) { return UTF8_ERROR; } + return UNCLOSED_STRING; +} + +// A document of at most 64 * BLOCKS bytes followed by SIMDJSON_PADDING bytes. +// Same result as the block loop and finish() in regular mode. +template +simdjson_inline error_code json_structural_indexer::index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept { + json_structural_indexer indexer(parser.structural_indexes.get()); + alignas(64) uint8_t block[64 * BLOCKS]; + buf_block_reader<64 * BLOCKS> reader(buf, len); + reader.get_remainder_padded(block); + simd::simd8x64 in_1(block); + json_block block_1 = indexer.scanner.next(in_1); + SIMDJSON_IF_CONSTEXPR (BLOCKS == 1) { + indexer.next(in_1, block_1, 0); + } else { + simd::simd8x64 in_2(block + 64); + json_block block_2 = indexer.scanner.next(in_2); + indexer.next(in_1, block_1, 0); + indexer.next(in_2, block_2, 64); + } + indexer.indexer.write(uint32_t(64 * BLOCKS - 64), indexer.prev_structurals); + const error_code error = indexer.scanner.finish(); + const uint32_t n = uint32_t(indexer.indexer.tail - parser.structural_indexes.get()); + parser.n_structural_indexes = n; + parser.structural_indexes[n] = uint32_t(len); + parser.structural_indexes[n + 1] = uint32_t(len); + parser.structural_indexes[n + 2] = 0; + parser.next_structural_index = 0; + if (simdjson_unlikely(error != SUCCESS)) { + return unclosed_string_error(buf, len, indexer.unescaped_chars_error != 0, indexer.checker.errors() != SUCCESS); + } + if (indexer.unescaped_chars_error) { return UNESCAPED_CHARS; } + // The bytes past len are spaces: no index exceeds len, unlike in finish(). + if (simdjson_unlikely(n == 0)) { return EMPTY; } + indexer.checker.check_eof(); + return indexer.checker.errors(); +} + template<> simdjson_inline void json_structural_indexer::step<128>(const uint8_t *block, buf_block_reader<128> &reader) noexcept { simd::simd8x64 in_1(block); @@ -50950,8 +51915,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // will be the quote and we want to make sure to omit it. if(have_unclosed_string) { parser.n_structural_indexes--; - // a valid JSON file cannot have zero structural indexes - we should have found something - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } // We truncate the input to the end of the last complete document (or zero). const bool partial_scalar = !have_unclosed_string && ends_with_partial_scalar(parser, len); @@ -51048,7 +52014,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Comma-delimited: filter root-level commas, use comma positions for batch boundaries if(have_unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } uint32_t next_batch_start = uint32_t(len); auto new_structural_indexes = filter_comma_delimited(parser, len, false, next_batch_start); @@ -52895,6 +53863,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lasx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lasx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -52904,14 +53873,11 @@ namespace lasx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -53163,6 +54129,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[32]; + std::memset(block, fill, 32); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -53735,10 +54709,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -53786,8 +54756,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -53981,6 +54951,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -54572,6 +55543,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -54625,19 +55605,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -54645,7 +55643,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -55026,10 +56026,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -55076,10 +56074,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -55131,10 +56127,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -55176,10 +56170,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -56003,6 +56995,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lasx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lasx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -56012,14 +57005,11 @@ namespace lasx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -56271,6 +57261,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[32]; + std::memset(block, fill, 32); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -56646,6 +57644,14 @@ struct buf_block_reader { * with full-width stores that the loads can forward from. */ simdjson_inline size_t get_remainder_padded(uint8_t *dst) const; + /** + * Like get_remainder, but reads only the input bytes: no padding is needed. + * + * The block is put together in vector registers and written with + * full-width stores, so that the loads that read it back are forwarded from + * the stores (see get_remainder_padded). + */ + simdjson_inline size_t get_remainder_unpadded(uint8_t *dst) const; simdjson_inline void advance(); private: const uint8_t *buf; @@ -56710,6 +57716,25 @@ simdjson_inline size_t buf_block_reader::get_remainder_padded(uint8_t return remaining; } +template +simdjson_inline size_t buf_block_reader::get_remainder_unpadded(uint8_t *dst) const { + const size_t remaining = len - idx; + constexpr size_t width = sizeof(simd::simd8); + for (size_t off = 0; off < STEP_SIZE; off += width) { + if (off + width <= remaining) { + const simd::simd8 v = simd::simd8::load(buf + idx + off); + v.store(dst + off); + } else if (off < remaining) { + const simd::simd8 v = simd::simd8::load_partial(buf + idx + off, remaining - off, buf, 0x20); + v.store(dst + off); + } else { + const simd::simd8 v = simd::simd8::splat(0x20); + v.store(dst + off); + } + } + return remaining; +} + template simdjson_inline void buf_block_reader::advance() { idx += STEP_SIZE; @@ -57628,11 +58653,9 @@ simdjson_inline uint32_t find_next_document_index_json_sequence( // Phase 2: Determine batch boundaries based on RS positions if (is_final) { - // Final batch: all documents are complete (last one ends at EOF). - // In json_sequence mode, RS markers define document boundaries, so all - // remaining structurals form complete documents. Return them all directly. - // (Calling find_next_document_index() would fail for scalar documents.) - return parser.n_structural_indexes; + // A cut number must not be parsed into padding the caller does not + // initialize. Leave that record to truncated_bytes(), as streaming_final does. + return find_next_document_index(parser); } // Partial batch: need to find complete documents only. @@ -57751,9 +58774,13 @@ simdjson_inline uint32_t filter_comma_delimited( // A document ending with a root comma is complete. if (root_comma_count == 0) { // No root commas found; we cannot confirm any document is complete. - // The whole batch might be one incomplete document. - // Return DOCUMENT_TOO_LARGE if content was found (write_idx > 0), 0 if only commas. - return (parser.n_structural_indexes > 0) ? DOCUMENT_TOO_LARGE : 0; + // The whole batch might be one incomplete document. If white space comes + // before it, a batch that starts at the document may hold it. + if (parser.structural_indexes[0] > 0) { + next_batch_start = parser.structural_indexes[0]; + return 0; + } + return DOCUMENT_TOO_LARGE; } // We have at least one root comma. Documents before the last comma are complete. @@ -57822,7 +58849,12 @@ class json_minifier { simdjson_inline void json_minifier::next(const simd::simd8x64& in, const json_block& block) { uint64_t mask = block.whitespace(); - dst += in.compress(mask, dst); + if (simdjson_unlikely(mask == 0)) { + in.store(dst); + dst += 64; + } else { + dst += in.compress(mask, dst); + } } simdjson_warn_unused simdjson_inline error_code json_minifier::finish(uint8_t *dst_start, size_t &dst_len) { @@ -57838,8 +58870,16 @@ simdjson_inline void json_minifier::step<128>(const uint8_t *block_buf, buf_bloc simd::simd8x64 in_2(block_buf+64); json_block block_1 = scanner.next(in_1); json_block block_2 = scanner.next(in_2); - this->next(in_1, block_1); - this->next(in_2, block_2); + const uint64_t mask_1 = block_1.whitespace(); + const uint64_t mask_2 = block_2.whitespace(); + if (simdjson_unlikely((mask_1 | mask_2) == 0)) { + in_1.store(dst); + in_2.store(dst + 64); + dst += 128; + } else { + dst += in_1.compress(mask_1, dst); + dst += in_2.compress(mask_2, dst); + } reader.advance(); } @@ -57862,12 +58902,12 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s } // Index the last (remainder) block, padded with spaces - uint8_t block[STEP_SIZE]; - size_t remaining_bytes = reader.get_remainder(block); + simdjson_indeterminate uint8_t block[STEP_SIZE]; + size_t remaining_bytes = reader.get_remainder_unpadded(block); if (remaining_bytes > 0) { // We do not want to write directly to the output stream. Rather, we write // to a local buffer (for safety). - uint8_t out_block[STEP_SIZE]; + simdjson_indeterminate uint8_t out_block[STEP_SIZE]; uint8_t * const guarded_dst{minifier.dst}; minifier.dst = out_block; minifier.step(block, reader); @@ -57917,8 +58957,8 @@ bool generic_validate_utf8(const uint8_t * input, size_t length) { c.check_next_input(in); reader.advance(); } - uint8_t block[64]{}; - reader.get_remainder(block); + uint8_t block[64]; + reader.get_remainder_unpadded(block); simd::simd8x64 in(block); c.check_next_input(in); reader.advance(); @@ -58079,6 +59119,8 @@ class json_structural_indexer { static error_code index(const uint8_t *buf, size_t len, dom_parser_implementation &parser, stage1_mode partial) noexcept; private: + template + static error_code index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept; simdjson_inline json_structural_indexer(uint32_t *structural_indexes); template simdjson_inline void step(const uint8_t *block, buf_block_reader &reader) noexcept; @@ -58137,6 +59179,15 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa if (simdjson_unlikely(len > parser.capacity())) { return CAPACITY; } // We guard the rest of the code so that we can assume that len > 0 throughout. if (len == 0) { return EMPTY; } + // Lone atoms only on a complete (non-streaming) buffer. Streaming windows + // have different truncation and partial-scalar rules. + if (partial == stage1_mode::regular && len <= 64 && buf[0] != '{' && buf[0] != '[' && buf[0] != '"') { + error_code atom = simdjson::internal::try_stage1_lone_atom(parser, buf, len); + if (atom != UNINITIALIZED) { return atom; } + } + if (partial == stage1_mode::regular && !parser._unpadded && len <= 128) { + return len <= 64 ? index_small<1>(buf, len, parser) : index_small<2>(buf, len, parser); + } if (is_streaming(partial)) { len = trim_partial_utf8(buf, len); // If you end up with an empty window after trimming @@ -58153,13 +59204,56 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa } // Take care of the last block (will always be there unless file is empty which is // not supposed to happen.) - uint8_t block[STEP_SIZE]; + simdjson_indeterminate uint8_t block[STEP_SIZE]; const size_t remaining = parser._unpadded ? reader.get_remainder(block) : reader.get_remainder_padded(block); if (simdjson_unlikely(remaining == 0)) { return UNEXPECTED_ERROR; } indexer.step(block, reader); return indexer.finish(parser, reader.block_index(), len, partial); } +// The error of a document that has an unclosed string, in regular mode. +simdjson_never_inline error_code unclosed_string_error(const uint8_t *buf, size_t len, bool unescaped_chars, bool utf8_suspect) noexcept { + if (unescaped_chars) { return UNESCAPED_CHARS; } + if (utf8_suspect && !generic_validate_utf8(buf, trim_partial_utf8(buf, len))) { return UTF8_ERROR; } + return UNCLOSED_STRING; +} + +// A document of at most 64 * BLOCKS bytes followed by SIMDJSON_PADDING bytes. +// Same result as the block loop and finish() in regular mode. +template +simdjson_inline error_code json_structural_indexer::index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept { + json_structural_indexer indexer(parser.structural_indexes.get()); + alignas(64) uint8_t block[64 * BLOCKS]; + buf_block_reader<64 * BLOCKS> reader(buf, len); + reader.get_remainder_padded(block); + simd::simd8x64 in_1(block); + json_block block_1 = indexer.scanner.next(in_1); + SIMDJSON_IF_CONSTEXPR (BLOCKS == 1) { + indexer.next(in_1, block_1, 0); + } else { + simd::simd8x64 in_2(block + 64); + json_block block_2 = indexer.scanner.next(in_2); + indexer.next(in_1, block_1, 0); + indexer.next(in_2, block_2, 64); + } + indexer.indexer.write(uint32_t(64 * BLOCKS - 64), indexer.prev_structurals); + const error_code error = indexer.scanner.finish(); + const uint32_t n = uint32_t(indexer.indexer.tail - parser.structural_indexes.get()); + parser.n_structural_indexes = n; + parser.structural_indexes[n] = uint32_t(len); + parser.structural_indexes[n + 1] = uint32_t(len); + parser.structural_indexes[n + 2] = 0; + parser.next_structural_index = 0; + if (simdjson_unlikely(error != SUCCESS)) { + return unclosed_string_error(buf, len, indexer.unescaped_chars_error != 0, indexer.checker.errors() != SUCCESS); + } + if (indexer.unescaped_chars_error) { return UNESCAPED_CHARS; } + // The bytes past len are spaces: no index exceeds len, unlike in finish(). + if (simdjson_unlikely(n == 0)) { return EMPTY; } + indexer.checker.check_eof(); + return indexer.checker.errors(); +} + template<> simdjson_inline void json_structural_indexer::step<128>(const uint8_t *block, buf_block_reader<128> &reader) noexcept { simd::simd8x64 in_1(block); @@ -58265,8 +59359,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // will be the quote and we want to make sure to omit it. if(have_unclosed_string) { parser.n_structural_indexes--; - // a valid JSON file cannot have zero structural indexes - we should have found something - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } // We truncate the input to the end of the last complete document (or zero). const bool partial_scalar = !have_unclosed_string && ends_with_partial_scalar(parser, len); @@ -58363,7 +59458,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Comma-delimited: filter root-level commas, use comma positions for batch boundaries if(have_unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } uint32_t next_batch_start = uint32_t(len); auto new_structural_indexes = filter_comma_delimited(parser, len, false, next_batch_start); @@ -60162,6 +61259,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lsx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lsx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -60171,14 +61269,11 @@ namespace lsx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -60403,6 +61498,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -60987,10 +62090,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -61038,8 +62137,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -61233,6 +62332,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -61824,6 +62924,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -61877,19 +62986,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -61897,7 +63024,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -62278,10 +63407,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -62328,10 +63455,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -62383,10 +63508,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -62428,10 +63551,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -63229,6 +64350,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lsx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lsx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -63238,14 +64360,11 @@ namespace lsx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -63470,6 +64589,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -63857,6 +64984,14 @@ struct buf_block_reader { * with full-width stores that the loads can forward from. */ simdjson_inline size_t get_remainder_padded(uint8_t *dst) const; + /** + * Like get_remainder, but reads only the input bytes: no padding is needed. + * + * The block is put together in vector registers and written with + * full-width stores, so that the loads that read it back are forwarded from + * the stores (see get_remainder_padded). + */ + simdjson_inline size_t get_remainder_unpadded(uint8_t *dst) const; simdjson_inline void advance(); private: const uint8_t *buf; @@ -63921,6 +65056,25 @@ simdjson_inline size_t buf_block_reader::get_remainder_padded(uint8_t return remaining; } +template +simdjson_inline size_t buf_block_reader::get_remainder_unpadded(uint8_t *dst) const { + const size_t remaining = len - idx; + constexpr size_t width = sizeof(simd::simd8); + for (size_t off = 0; off < STEP_SIZE; off += width) { + if (off + width <= remaining) { + const simd::simd8 v = simd::simd8::load(buf + idx + off); + v.store(dst + off); + } else if (off < remaining) { + const simd::simd8 v = simd::simd8::load_partial(buf + idx + off, remaining - off, buf, 0x20); + v.store(dst + off); + } else { + const simd::simd8 v = simd::simd8::splat(0x20); + v.store(dst + off); + } + } + return remaining; +} + template simdjson_inline void buf_block_reader::advance() { idx += STEP_SIZE; @@ -64839,11 +65993,9 @@ simdjson_inline uint32_t find_next_document_index_json_sequence( // Phase 2: Determine batch boundaries based on RS positions if (is_final) { - // Final batch: all documents are complete (last one ends at EOF). - // In json_sequence mode, RS markers define document boundaries, so all - // remaining structurals form complete documents. Return them all directly. - // (Calling find_next_document_index() would fail for scalar documents.) - return parser.n_structural_indexes; + // A cut number must not be parsed into padding the caller does not + // initialize. Leave that record to truncated_bytes(), as streaming_final does. + return find_next_document_index(parser); } // Partial batch: need to find complete documents only. @@ -64962,9 +66114,13 @@ simdjson_inline uint32_t filter_comma_delimited( // A document ending with a root comma is complete. if (root_comma_count == 0) { // No root commas found; we cannot confirm any document is complete. - // The whole batch might be one incomplete document. - // Return DOCUMENT_TOO_LARGE if content was found (write_idx > 0), 0 if only commas. - return (parser.n_structural_indexes > 0) ? DOCUMENT_TOO_LARGE : 0; + // The whole batch might be one incomplete document. If white space comes + // before it, a batch that starts at the document may hold it. + if (parser.structural_indexes[0] > 0) { + next_batch_start = parser.structural_indexes[0]; + return 0; + } + return DOCUMENT_TOO_LARGE; } // We have at least one root comma. Documents before the last comma are complete. @@ -65033,7 +66189,12 @@ class json_minifier { simdjson_inline void json_minifier::next(const simd::simd8x64& in, const json_block& block) { uint64_t mask = block.whitespace(); - dst += in.compress(mask, dst); + if (simdjson_unlikely(mask == 0)) { + in.store(dst); + dst += 64; + } else { + dst += in.compress(mask, dst); + } } simdjson_warn_unused simdjson_inline error_code json_minifier::finish(uint8_t *dst_start, size_t &dst_len) { @@ -65049,8 +66210,16 @@ simdjson_inline void json_minifier::step<128>(const uint8_t *block_buf, buf_bloc simd::simd8x64 in_2(block_buf+64); json_block block_1 = scanner.next(in_1); json_block block_2 = scanner.next(in_2); - this->next(in_1, block_1); - this->next(in_2, block_2); + const uint64_t mask_1 = block_1.whitespace(); + const uint64_t mask_2 = block_2.whitespace(); + if (simdjson_unlikely((mask_1 | mask_2) == 0)) { + in_1.store(dst); + in_2.store(dst + 64); + dst += 128; + } else { + dst += in_1.compress(mask_1, dst); + dst += in_2.compress(mask_2, dst); + } reader.advance(); } @@ -65073,12 +66242,12 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s } // Index the last (remainder) block, padded with spaces - uint8_t block[STEP_SIZE]; - size_t remaining_bytes = reader.get_remainder(block); + simdjson_indeterminate uint8_t block[STEP_SIZE]; + size_t remaining_bytes = reader.get_remainder_unpadded(block); if (remaining_bytes > 0) { // We do not want to write directly to the output stream. Rather, we write // to a local buffer (for safety). - uint8_t out_block[STEP_SIZE]; + simdjson_indeterminate uint8_t out_block[STEP_SIZE]; uint8_t * const guarded_dst{minifier.dst}; minifier.dst = out_block; minifier.step(block, reader); @@ -65128,8 +66297,8 @@ bool generic_validate_utf8(const uint8_t * input, size_t length) { c.check_next_input(in); reader.advance(); } - uint8_t block[64]{}; - reader.get_remainder(block); + uint8_t block[64]; + reader.get_remainder_unpadded(block); simd::simd8x64 in(block); c.check_next_input(in); reader.advance(); @@ -65290,6 +66459,8 @@ class json_structural_indexer { static error_code index(const uint8_t *buf, size_t len, dom_parser_implementation &parser, stage1_mode partial) noexcept; private: + template + static error_code index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept; simdjson_inline json_structural_indexer(uint32_t *structural_indexes); template simdjson_inline void step(const uint8_t *block, buf_block_reader &reader) noexcept; @@ -65348,6 +66519,15 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa if (simdjson_unlikely(len > parser.capacity())) { return CAPACITY; } // We guard the rest of the code so that we can assume that len > 0 throughout. if (len == 0) { return EMPTY; } + // Lone atoms only on a complete (non-streaming) buffer. Streaming windows + // have different truncation and partial-scalar rules. + if (partial == stage1_mode::regular && len <= 64 && buf[0] != '{' && buf[0] != '[' && buf[0] != '"') { + error_code atom = simdjson::internal::try_stage1_lone_atom(parser, buf, len); + if (atom != UNINITIALIZED) { return atom; } + } + if (partial == stage1_mode::regular && !parser._unpadded && len <= 128) { + return len <= 64 ? index_small<1>(buf, len, parser) : index_small<2>(buf, len, parser); + } if (is_streaming(partial)) { len = trim_partial_utf8(buf, len); // If you end up with an empty window after trimming @@ -65364,13 +66544,56 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa } // Take care of the last block (will always be there unless file is empty which is // not supposed to happen.) - uint8_t block[STEP_SIZE]; + simdjson_indeterminate uint8_t block[STEP_SIZE]; const size_t remaining = parser._unpadded ? reader.get_remainder(block) : reader.get_remainder_padded(block); if (simdjson_unlikely(remaining == 0)) { return UNEXPECTED_ERROR; } indexer.step(block, reader); return indexer.finish(parser, reader.block_index(), len, partial); } +// The error of a document that has an unclosed string, in regular mode. +simdjson_never_inline error_code unclosed_string_error(const uint8_t *buf, size_t len, bool unescaped_chars, bool utf8_suspect) noexcept { + if (unescaped_chars) { return UNESCAPED_CHARS; } + if (utf8_suspect && !generic_validate_utf8(buf, trim_partial_utf8(buf, len))) { return UTF8_ERROR; } + return UNCLOSED_STRING; +} + +// A document of at most 64 * BLOCKS bytes followed by SIMDJSON_PADDING bytes. +// Same result as the block loop and finish() in regular mode. +template +simdjson_inline error_code json_structural_indexer::index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept { + json_structural_indexer indexer(parser.structural_indexes.get()); + alignas(64) uint8_t block[64 * BLOCKS]; + buf_block_reader<64 * BLOCKS> reader(buf, len); + reader.get_remainder_padded(block); + simd::simd8x64 in_1(block); + json_block block_1 = indexer.scanner.next(in_1); + SIMDJSON_IF_CONSTEXPR (BLOCKS == 1) { + indexer.next(in_1, block_1, 0); + } else { + simd::simd8x64 in_2(block + 64); + json_block block_2 = indexer.scanner.next(in_2); + indexer.next(in_1, block_1, 0); + indexer.next(in_2, block_2, 64); + } + indexer.indexer.write(uint32_t(64 * BLOCKS - 64), indexer.prev_structurals); + const error_code error = indexer.scanner.finish(); + const uint32_t n = uint32_t(indexer.indexer.tail - parser.structural_indexes.get()); + parser.n_structural_indexes = n; + parser.structural_indexes[n] = uint32_t(len); + parser.structural_indexes[n + 1] = uint32_t(len); + parser.structural_indexes[n + 2] = 0; + parser.next_structural_index = 0; + if (simdjson_unlikely(error != SUCCESS)) { + return unclosed_string_error(buf, len, indexer.unescaped_chars_error != 0, indexer.checker.errors() != SUCCESS); + } + if (indexer.unescaped_chars_error) { return UNESCAPED_CHARS; } + // The bytes past len are spaces: no index exceeds len, unlike in finish(). + if (simdjson_unlikely(n == 0)) { return EMPTY; } + indexer.checker.check_eof(); + return indexer.checker.errors(); +} + template<> simdjson_inline void json_structural_indexer::step<128>(const uint8_t *block, buf_block_reader<128> &reader) noexcept { simd::simd8x64 in_1(block); @@ -65476,8 +66699,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // will be the quote and we want to make sure to omit it. if(have_unclosed_string) { parser.n_structural_indexes--; - // a valid JSON file cannot have zero structural indexes - we should have found something - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } // We truncate the input to the end of the last complete document (or zero). const bool partial_scalar = !have_unclosed_string && ends_with_partial_scalar(parser, len); @@ -65574,7 +66798,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Comma-delimited: filter root-level commas, use comma positions for batch boundaries if(have_unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } uint32_t next_batch_start = uint32_t(len); auto new_structural_indexes = filter_comma_delimited(parser, len, false, next_batch_start); @@ -67480,6 +68706,14 @@ namespace simd { simdjson_inline simd8() : simd8(zero()) {} simdjson_inline simd8(const uint8_t values[VL8]) : simd8(load(values)) {} simdjson_inline simd8(uint8_t _value) : simd8(splat(_value)) {} + // The n < VL8 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[VL8]; + std::memset(block, fill, VL8); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8(simd8 mask) : value(__riscv_vmerge_vxm_u8m1(zero(), -1, (vbool_t)mask, VL8)) {} simdjson_inline operator const vuint8_t&() const { return this->value; } @@ -67816,6 +69050,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/rvv-vls/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -67831,7 +69066,6 @@ namespace simdjson { namespace rvv_vls { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; @@ -67840,9 +69074,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { #else val = __riscv_vmv_x(__riscv_vreinterpret_u64m1(__riscv_vlmul_ext_u8m1(__riscv_vle8_v_u8mf2((uint8_t*)chars, 8)))); #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -68236,10 +69468,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -68287,8 +69515,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -68482,6 +69710,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -69073,6 +70302,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -69126,19 +70364,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -69146,7 +70402,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -69527,10 +70785,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -69577,10 +70833,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -69632,10 +70886,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -69677,10 +70929,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -70589,6 +71839,14 @@ namespace simd { simdjson_inline simd8() : simd8(zero()) {} simdjson_inline simd8(const uint8_t values[VL8]) : simd8(load(values)) {} simdjson_inline simd8(uint8_t _value) : simd8(splat(_value)) {} + // The n < VL8 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[VL8]; + std::memset(block, fill, VL8); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8(simd8 mask) : value(__riscv_vmerge_vxm_u8m1(zero(), -1, (vbool_t)mask, VL8)) {} simdjson_inline operator const vuint8_t&() const { return this->value; } @@ -70925,6 +72183,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/rvv-vls/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -70940,7 +72199,6 @@ namespace simdjson { namespace rvv_vls { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; @@ -70949,9 +72207,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { #else val = __riscv_vmv_x(__riscv_vreinterpret_u64m1(__riscv_vlmul_ext_u8m1(__riscv_vle8_v_u8mf2((uint8_t*)chars, 8)))); #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -71079,6 +72335,14 @@ namespace simd { simdjson_inline simd8() : simd8(zero()) {} simdjson_inline simd8(const uint8_t values[VL8]) : simd8(load(values)) {} simdjson_inline simd8(uint8_t _value) : simd8(splat(_value)) {} + // The n < VL8 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[VL8]; + std::memset(block, fill, VL8); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8(simd8 mask) : value(__riscv_vmerge_vxm_u8m1(zero(), -1, (vbool_t)mask, VL8)) {} simdjson_inline operator const vuint8_t&() const { return this->value; } @@ -71532,6 +72796,14 @@ struct buf_block_reader { * with full-width stores that the loads can forward from. */ simdjson_inline size_t get_remainder_padded(uint8_t *dst) const; + /** + * Like get_remainder, but reads only the input bytes: no padding is needed. + * + * The block is put together in vector registers and written with + * full-width stores, so that the loads that read it back are forwarded from + * the stores (see get_remainder_padded). + */ + simdjson_inline size_t get_remainder_unpadded(uint8_t *dst) const; simdjson_inline void advance(); private: const uint8_t *buf; @@ -71596,6 +72868,25 @@ simdjson_inline size_t buf_block_reader::get_remainder_padded(uint8_t return remaining; } +template +simdjson_inline size_t buf_block_reader::get_remainder_unpadded(uint8_t *dst) const { + const size_t remaining = len - idx; + constexpr size_t width = sizeof(simd::simd8); + for (size_t off = 0; off < STEP_SIZE; off += width) { + if (off + width <= remaining) { + const simd::simd8 v = simd::simd8::load(buf + idx + off); + v.store(dst + off); + } else if (off < remaining) { + const simd::simd8 v = simd::simd8::load_partial(buf + idx + off, remaining - off, buf, 0x20); + v.store(dst + off); + } else { + const simd::simd8 v = simd::simd8::splat(0x20); + v.store(dst + off); + } + } + return remaining; +} + template simdjson_inline void buf_block_reader::advance() { idx += STEP_SIZE; @@ -72514,11 +73805,9 @@ simdjson_inline uint32_t find_next_document_index_json_sequence( // Phase 2: Determine batch boundaries based on RS positions if (is_final) { - // Final batch: all documents are complete (last one ends at EOF). - // In json_sequence mode, RS markers define document boundaries, so all - // remaining structurals form complete documents. Return them all directly. - // (Calling find_next_document_index() would fail for scalar documents.) - return parser.n_structural_indexes; + // A cut number must not be parsed into padding the caller does not + // initialize. Leave that record to truncated_bytes(), as streaming_final does. + return find_next_document_index(parser); } // Partial batch: need to find complete documents only. @@ -72637,9 +73926,13 @@ simdjson_inline uint32_t filter_comma_delimited( // A document ending with a root comma is complete. if (root_comma_count == 0) { // No root commas found; we cannot confirm any document is complete. - // The whole batch might be one incomplete document. - // Return DOCUMENT_TOO_LARGE if content was found (write_idx > 0), 0 if only commas. - return (parser.n_structural_indexes > 0) ? DOCUMENT_TOO_LARGE : 0; + // The whole batch might be one incomplete document. If white space comes + // before it, a batch that starts at the document may hold it. + if (parser.structural_indexes[0] > 0) { + next_batch_start = parser.structural_indexes[0]; + return 0; + } + return DOCUMENT_TOO_LARGE; } // We have at least one root comma. Documents before the last comma are complete. @@ -72708,7 +74001,12 @@ class json_minifier { simdjson_inline void json_minifier::next(const simd::simd8x64& in, const json_block& block) { uint64_t mask = block.whitespace(); - dst += in.compress(mask, dst); + if (simdjson_unlikely(mask == 0)) { + in.store(dst); + dst += 64; + } else { + dst += in.compress(mask, dst); + } } simdjson_warn_unused simdjson_inline error_code json_minifier::finish(uint8_t *dst_start, size_t &dst_len) { @@ -72724,8 +74022,16 @@ simdjson_inline void json_minifier::step<128>(const uint8_t *block_buf, buf_bloc simd::simd8x64 in_2(block_buf+64); json_block block_1 = scanner.next(in_1); json_block block_2 = scanner.next(in_2); - this->next(in_1, block_1); - this->next(in_2, block_2); + const uint64_t mask_1 = block_1.whitespace(); + const uint64_t mask_2 = block_2.whitespace(); + if (simdjson_unlikely((mask_1 | mask_2) == 0)) { + in_1.store(dst); + in_2.store(dst + 64); + dst += 128; + } else { + dst += in_1.compress(mask_1, dst); + dst += in_2.compress(mask_2, dst); + } reader.advance(); } @@ -72748,12 +74054,12 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s } // Index the last (remainder) block, padded with spaces - uint8_t block[STEP_SIZE]; - size_t remaining_bytes = reader.get_remainder(block); + simdjson_indeterminate uint8_t block[STEP_SIZE]; + size_t remaining_bytes = reader.get_remainder_unpadded(block); if (remaining_bytes > 0) { // We do not want to write directly to the output stream. Rather, we write // to a local buffer (for safety). - uint8_t out_block[STEP_SIZE]; + simdjson_indeterminate uint8_t out_block[STEP_SIZE]; uint8_t * const guarded_dst{minifier.dst}; minifier.dst = out_block; minifier.step(block, reader); @@ -72803,8 +74109,8 @@ bool generic_validate_utf8(const uint8_t * input, size_t length) { c.check_next_input(in); reader.advance(); } - uint8_t block[64]{}; - reader.get_remainder(block); + uint8_t block[64]; + reader.get_remainder_unpadded(block); simd::simd8x64 in(block); c.check_next_input(in); reader.advance(); @@ -72965,6 +74271,8 @@ class json_structural_indexer { static error_code index(const uint8_t *buf, size_t len, dom_parser_implementation &parser, stage1_mode partial) noexcept; private: + template + static error_code index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept; simdjson_inline json_structural_indexer(uint32_t *structural_indexes); template simdjson_inline void step(const uint8_t *block, buf_block_reader &reader) noexcept; @@ -73023,6 +74331,15 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa if (simdjson_unlikely(len > parser.capacity())) { return CAPACITY; } // We guard the rest of the code so that we can assume that len > 0 throughout. if (len == 0) { return EMPTY; } + // Lone atoms only on a complete (non-streaming) buffer. Streaming windows + // have different truncation and partial-scalar rules. + if (partial == stage1_mode::regular && len <= 64 && buf[0] != '{' && buf[0] != '[' && buf[0] != '"') { + error_code atom = simdjson::internal::try_stage1_lone_atom(parser, buf, len); + if (atom != UNINITIALIZED) { return atom; } + } + if (partial == stage1_mode::regular && !parser._unpadded && len <= 128) { + return len <= 64 ? index_small<1>(buf, len, parser) : index_small<2>(buf, len, parser); + } if (is_streaming(partial)) { len = trim_partial_utf8(buf, len); // If you end up with an empty window after trimming @@ -73039,13 +74356,56 @@ error_code json_structural_indexer::index(const uint8_t *buf, size_t len, dom_pa } // Take care of the last block (will always be there unless file is empty which is // not supposed to happen.) - uint8_t block[STEP_SIZE]; + simdjson_indeterminate uint8_t block[STEP_SIZE]; const size_t remaining = parser._unpadded ? reader.get_remainder(block) : reader.get_remainder_padded(block); if (simdjson_unlikely(remaining == 0)) { return UNEXPECTED_ERROR; } indexer.step(block, reader); return indexer.finish(parser, reader.block_index(), len, partial); } +// The error of a document that has an unclosed string, in regular mode. +simdjson_never_inline error_code unclosed_string_error(const uint8_t *buf, size_t len, bool unescaped_chars, bool utf8_suspect) noexcept { + if (unescaped_chars) { return UNESCAPED_CHARS; } + if (utf8_suspect && !generic_validate_utf8(buf, trim_partial_utf8(buf, len))) { return UTF8_ERROR; } + return UNCLOSED_STRING; +} + +// A document of at most 64 * BLOCKS bytes followed by SIMDJSON_PADDING bytes. +// Same result as the block loop and finish() in regular mode. +template +simdjson_inline error_code json_structural_indexer::index_small(const uint8_t *buf, size_t len, dom_parser_implementation &parser) noexcept { + json_structural_indexer indexer(parser.structural_indexes.get()); + alignas(64) uint8_t block[64 * BLOCKS]; + buf_block_reader<64 * BLOCKS> reader(buf, len); + reader.get_remainder_padded(block); + simd::simd8x64 in_1(block); + json_block block_1 = indexer.scanner.next(in_1); + SIMDJSON_IF_CONSTEXPR (BLOCKS == 1) { + indexer.next(in_1, block_1, 0); + } else { + simd::simd8x64 in_2(block + 64); + json_block block_2 = indexer.scanner.next(in_2); + indexer.next(in_1, block_1, 0); + indexer.next(in_2, block_2, 64); + } + indexer.indexer.write(uint32_t(64 * BLOCKS - 64), indexer.prev_structurals); + const error_code error = indexer.scanner.finish(); + const uint32_t n = uint32_t(indexer.indexer.tail - parser.structural_indexes.get()); + parser.n_structural_indexes = n; + parser.structural_indexes[n] = uint32_t(len); + parser.structural_indexes[n + 1] = uint32_t(len); + parser.structural_indexes[n + 2] = 0; + parser.next_structural_index = 0; + if (simdjson_unlikely(error != SUCCESS)) { + return unclosed_string_error(buf, len, indexer.unescaped_chars_error != 0, indexer.checker.errors() != SUCCESS); + } + if (indexer.unescaped_chars_error) { return UNESCAPED_CHARS; } + // The bytes past len are spaces: no index exceeds len, unlike in finish(). + if (simdjson_unlikely(n == 0)) { return EMPTY; } + indexer.checker.check_eof(); + return indexer.checker.errors(); +} + template<> simdjson_inline void json_structural_indexer::step<128>(const uint8_t *block, buf_block_reader<128> &reader) noexcept { simd::simd8x64 in_1(block); @@ -73151,8 +74511,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // will be the quote and we want to make sure to omit it. if(have_unclosed_string) { parser.n_structural_indexes--; - // a valid JSON file cannot have zero structural indexes - we should have found something - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } // We truncate the input to the end of the last complete document (or zero). const bool partial_scalar = !have_unclosed_string && ends_with_partial_scalar(parser, len); @@ -73249,7 +74610,9 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Comma-delimited: filter root-level commas, use comma positions for batch boundaries if(have_unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } uint32_t next_batch_start = uint32_t(len); auto new_structural_indexes = filter_comma_delimited(parser, len, false, next_batch_start); @@ -75036,6 +76399,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/fallback/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -75051,14 +76415,11 @@ namespace simdjson { namespace fallback { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; - memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + std::memcpy(&val, chars, sizeof(uint64_t)); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -75484,10 +76845,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -75535,8 +76892,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -75730,6 +77087,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -76321,6 +77679,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -76374,19 +77741,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -76394,7 +77779,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -76775,10 +78162,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -76825,10 +78210,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -76880,10 +78263,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -76925,10 +78306,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -77726,6 +79105,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/fallback/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -77741,14 +79121,11 @@ namespace simdjson { namespace fallback { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; - memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + std::memcpy(&val, chars, sizeof(uint64_t)); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -78073,11 +79450,9 @@ simdjson_inline uint32_t find_next_document_index_json_sequence( // Phase 2: Determine batch boundaries based on RS positions if (is_final) { - // Final batch: all documents are complete (last one ends at EOF). - // In json_sequence mode, RS markers define document boundaries, so all - // remaining structurals form complete documents. Return them all directly. - // (Calling find_next_document_index() would fail for scalar documents.) - return parser.n_structural_indexes; + // A cut number must not be parsed into padding the caller does not + // initialize. Leave that record to truncated_bytes(), as streaming_final does. + return find_next_document_index(parser); } // Partial batch: need to find complete documents only. @@ -78196,9 +79571,13 @@ simdjson_inline uint32_t filter_comma_delimited( // A document ending with a root comma is complete. if (root_comma_count == 0) { // No root commas found; we cannot confirm any document is complete. - // The whole batch might be one incomplete document. - // Return DOCUMENT_TOO_LARGE if content was found (write_idx > 0), 0 if only commas. - return (parser.n_structural_indexes > 0) ? DOCUMENT_TOO_LARGE : 0; + // The whole batch might be one incomplete document. If white space comes + // before it, a batch that starts at the document may hold it. + if (parser.structural_indexes[0] > 0) { + next_batch_start = parser.structural_indexes[0]; + return 0; + } + return DOCUMENT_TOO_LARGE; } // We have at least one root comma. Documents before the last comma are complete. @@ -79905,7 +81284,9 @@ simdjson_warn_unused simdjson_inline error_code scan() { if (partial == stage1_mode::streaming_partial) { if(unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } // We truncate the input to the end of the last complete document (or zero). // See json_structural_indexer.h for ends_with_unfinished_document(). @@ -79996,7 +81377,9 @@ simdjson_warn_unused simdjson_inline error_code scan() { // Comma-delimited: filter root-level commas, use comma positions for batch boundaries if(unclosed_string) { parser.n_structural_indexes--; - if (simdjson_unlikely(parser.n_structural_indexes == 0)) { return CAPACITY; } + if (simdjson_unlikely(parser.n_structural_indexes == 0)) { + return parser.structural_indexes[0] == 0 ? CAPACITY : EMPTY; + } } uint32_t next_batch_start = uint32_t(len); auto new_structural_indexes = filter_comma_delimited(parser, len, false, next_batch_start); @@ -80089,6 +81472,41 @@ simdjson_warn_unused error_code implementation::minify(const uint8_t *buf, size_ uint8_t quote = 0; uint8_t nonescape = 1; + // Bytes 0x80 where the byte of word equals c. + const auto bytes_equal = [](uint64_t word, uint8_t c) -> uint64_t { + const uint64_t x = word ^ (0x0101010101010101 * c); + return ~(((x & 0x7F7F7F7F7F7F7F7F) + 0x7F7F7F7F7F7F7F7F) | x | 0x7F7F7F7F7F7F7F7F); + }; + // A word without quotes or backslashes leaves the string state unchanged: + // within a string it is copied, outside it loses its white space. + while (i + 8 <= len) { + uint64_t word; + std::memcpy(&word, buf + i, 8); + if (bytes_equal(word, '"') | bytes_equal(word, '\\')) { + for (size_t end = i + 8; i < end; i++) { + unsigned char c = buf[i]; + uint8_t *meta = jump_table + 3 * c; + quote = quote ^ (meta[0] & nonescape); + dst[pos] = c; + pos += meta[2] | quote; + nonescape = uint8_t(~nonescape) | (meta[1]); + } + continue; + } + nonescape = 1; + if (quote || !(bytes_equal(word, ' ') | bytes_equal(word, '\n') | bytes_equal(word, '\r') | bytes_equal(word, '\t'))) { + std::memcpy(dst + pos, &word, 8); + pos += 8; + i += 8; + } else { + for (size_t end = i + 8; i < end; i++) { + unsigned char c = buf[i]; + dst[pos] = c; + pos += jump_table[3 * c + 2]; + } + } + } + while (i < len) { unsigned char c = buf[i]; uint8_t *meta = jump_table + 3 * c; diff --git a/deps/simdjson/simdjson.h b/deps/simdjson/simdjson.h index 49f66b687dcf..a27a5d4f94a3 100644 --- a/deps/simdjson/simdjson.h +++ b/deps/simdjson/simdjson.h @@ -1,4 +1,4 @@ -/* auto-generated on 2026-11-14 18:54:03 -0500. version 5.2.0 Do not edit! */ +/* auto-generated on 2026-11-22 13:48:29 -0500. version 5.3.0 Do not edit! */ /* including simdjson.h: */ /* begin file simdjson.h */ #ifndef SIMDJSON_H @@ -642,10 +642,9 @@ namespace internal { * @private * Scratch capacity that every caller of to_chars must provide. * - * The emitted decimal is at most ~24 characters, but dragonbox() and - * format_buffer() intentionally write past the logical end with fixed-size - * 16/17-byte memcpy/memset operations so the compiler can inline them (no - * libc mem* dispatch with size-class branches). The extra bytes are required + * The emitted decimal is at most ~24 characters, but to_chars() intentionally + * writes past the logical end with fixed-size 8- and 16-byte stores, so that + * the layout needs no length-dependent branches. The extra bytes are required * for safety of those over-writes; do not shrink this below 40. * See src/to_chars.cpp and #2805. */ @@ -692,6 +691,10 @@ float from_chars_float(const char *first) noexcept; #define SIMDJSON_ENABLE_NAN_INF 0 #endif +#ifndef SIMDJSON_ALLOW_TRAILING_COMMAS +#define SIMDJSON_ALLOW_TRAILING_COMMAS 0 +#endif + } // namespace simdjson #if defined(__GNUC__) @@ -2739,6 +2742,25 @@ namespace std { #else #define simdjson_lifetime_bound #endif + +// C++26 (P2795R5) and -ftrivial-auto-var-init zero-fill local variables that +// have no initializer. simdjson_indeterminate opts a local out of that. Use it +// only on buffers that the code writes before it reads them. +#if defined(SIMDJSON_CPLUSPLUS26) && defined(__has_cpp_attribute) +#if __has_cpp_attribute(indeterminate) +#define simdjson_indeterminate [[indeterminate]] +#endif +#endif + +#if !defined(simdjson_indeterminate) && defined(__has_attribute) +#if __has_attribute(uninitialized) +#define simdjson_indeterminate __attribute__((uninitialized)) +#endif +#endif + +#ifndef simdjson_indeterminate +#define simdjson_indeterminate +#endif #endif // SIMDJSON_COMMON_DEFS_H /* end file simdjson/common_defs.h */ @@ -2752,7 +2774,7 @@ namespace std { #define SIMDJSON_SIMDJSON_VERSION_H /** The version of simdjson being used (major.minor.revision) */ -#define SIMDJSON_VERSION "5.2.0" +#define SIMDJSON_VERSION "5.3.0" namespace simdjson { enum { @@ -2763,7 +2785,7 @@ enum { /** * The minor version (major.MINOR.revision) of simdjson being used. */ - SIMDJSON_VERSION_MINOR = 2, + SIMDJSON_VERSION_MINOR = 3, /** * The revision (major.minor.REVISION) of simdjson being used. */ @@ -3117,6 +3139,22 @@ struct simdjson_result : public internal::simdjson_result_base { return error; } + /** + * Provide a default value for a missing key. + * + * If the error is NO_SUCH_FIELD, returns a successful result holding default_value. + * Otherwise, returns this result unchanged: the value, or any other error + * (e.g., INCORRECT_TYPE, TAPE_ERROR) which is still reported. + * + * double z = obj["z"].get_double().default_if_missing(0.0); + * // or, without exceptions: + * double z; + * auto error = obj["z"].get_double().default_if_missing(0.0).get(z); + * + * @param default_value The value to use when the key is missing. + */ + simdjson_warn_unused simdjson_inline simdjson_result default_if_missing(T default_value) && noexcept; + /** * The error. */ @@ -3669,6 +3707,115 @@ simdjson_inline void assign_utf8(std::basic_string_view &r #endif // SIMDJSON_BASE_H /* end file simdjson/base.h */ +/* including simdjson/buffer_allocator.h: #include "simdjson/buffer_allocator.h" */ +/* begin file simdjson/buffer_allocator.h */ +#ifndef SIMDJSON_BUFFER_ALLOCATOR_H +#define SIMDJSON_BUFFER_ALLOCATOR_H + +/* skipped duplicate #include "simdjson/base.h" */ + +#include +#include + +namespace simdjson { + +/** + * Allocates the buffers that a parser keeps between documents and that grow + * with the largest document it parses: the structural indexes, the On-Demand + * string buffer, and the DOM tape and string buffer. + * + * Both functions must be noexcept. allocate returns memory aligned at least + * as malloc would align it, or nullptr on failure, in which case the parser + * returns MEMALLOC and keeps its previous buffers. deallocate receives the + * pointer, the size that was requested and the context. + * + * A parser allocates only when it grows, so a reused parser rarely calls the + * allocator. The allocator, and its context, must outlive every parser and + * document that holds memory from it. + */ +struct buffer_allocator { + void *(*allocate)(void *context, size_t size) noexcept; + void (*deallocate)(void *context, void *pointer, size_t size) noexcept; + void *context; +}; + +namespace internal { + +/** + * @private An owning array of trivial elements, from a buffer_allocator or, + * without one, from new[]. It frees itself through what allocated it. + */ +template class allocated_array { +public: + allocated_array() noexcept = default; + allocated_array(const allocated_array &) = delete; + allocated_array &operator=(const allocated_array &) = delete; + allocated_array(allocated_array &&other) noexcept + : data_{other.data_}, size_{other.size_}, allocator_{other.allocator_} { + other.data_ = nullptr; + other.size_ = 0; + other.allocator_ = nullptr; + } + allocated_array &operator=(allocated_array &&other) noexcept { + if (this != &other) { + reset(); + data_ = other.data_; + size_ = other.size_; + allocator_ = other.allocator_; + other.data_ = nullptr; + other.size_ = 0; + other.allocator_ = nullptr; + } + return *this; + } + ~allocated_array() noexcept { reset(); } + + /** Replace the content by count uninitialized elements; false on failure. */ + bool allocate(size_t count, const buffer_allocator *allocator) noexcept { + reset(); + if (allocator) { + if (count > size_t(-1) / sizeof(T)) { + return false; + } + data_ = static_cast(allocator->allocate(allocator->context, count * sizeof(T))); + } else { + data_ = new (std::nothrow) T[count]; + } + if (!data_) { + return false; + } + size_ = count; + allocator_ = allocator; + return true; + } + void reset() noexcept { + if (!data_) { + return; + } + if (allocator_) { + allocator_->deallocate(allocator_->context, data_, size_ * sizeof(T)); + } else { + delete[] data_; + } + data_ = nullptr; + size_ = 0; + allocator_ = nullptr; + } + simdjson_inline T *get() const noexcept { return data_; } + simdjson_inline T &operator[](size_t index) const noexcept { return data_[index]; } + simdjson_inline explicit operator bool() const noexcept { return data_ != nullptr; } + +private: + T *data_{nullptr}; + size_t size_{0}; + const buffer_allocator *allocator_{nullptr}; +}; + +} // namespace internal +} // namespace simdjson + +#endif // SIMDJSON_BUFFER_ALLOCATOR_H +/* end file simdjson/buffer_allocator.h */ /* skipped duplicate #include "simdjson/error.h" */ /* including simdjson/error-inl.h: #include "simdjson/error-inl.h" */ @@ -3839,6 +3986,13 @@ simdjson_result::get(T &value) && noexcept { return std::forward>(*this).get(value); } +template +simdjson_warn_unused simdjson_inline simdjson_result +simdjson_result::default_if_missing(T default_value) && noexcept { + if (error() == NO_SUCH_FIELD) { return simdjson_result(std::move(default_value)); } + return std::move(*this); +} + template simdjson_inline error_code simdjson_result::error() const noexcept { return internal::simdjson_result_base::error(); @@ -3941,6 +4095,7 @@ class atomic_ptr { /* skipped duplicate #include "simdjson/base.h" */ /* skipped duplicate #include "simdjson/error.h" */ +/* skipped duplicate #include "simdjson/buffer_allocator.h" */ #include namespace simdjson { @@ -4127,9 +4282,15 @@ class dom_parser_implementation { /** Number of structural indices passed from stage 1 to stage 2 */ uint32_t n_structural_indexes{0}; /** Structural indices passed from stage 1 to stage 2 */ - std::unique_ptr structural_indexes{}; + allocated_array structural_indexes{}; + /** Allocates structural_indexes when set_capacity grows them; nullptr uses new[]. */ + const buffer_allocator *allocator{nullptr}; /** Next structural index to parse */ uint32_t next_structural_index{0}; + /** Buffer passed to stage 1 (also set by the lone-atom fast path). */ + const uint8_t *buf{}; + /** Length passed to stage 1. */ + size_t len{0}; /** * The largest document this parser can support without reallocating. @@ -4204,6 +4365,76 @@ class dom_parser_implementation { simdjson_inline dom_parser_implementation &operator=(const dom_parser_implementation &other) noexcept = delete; }; // class dom_parser_implementation +// Stage-1 fast path for a single JSON atom (number / true / false / null) +// surrounded only by ASCII whitespace. Writes the one-entry structural tape +// and returns SUCCESS, returns EMPTY for an all-whitespace buffer, or +// returns UNINITIALIZED if the buffer is not that shape (caller must run +// the full indexer). json_structural_indexer::index calls it before the +// SIMD loop. +simdjson_never_inline error_code try_stage1_lone_atom(dom_parser_implementation &parser, const uint8_t *buf, size_t len) noexcept { + auto is_json_ws = [](uint8_t c) noexcept { + return c == ' ' || c == '\t' || c == '\n' || c == '\r'; + }; + size_t i = 0; + while (i < len && is_json_ws(buf[i])) { i++; } + if (i == len) { return EMPTY; } + const size_t atom = i; + const uint8_t c = buf[i]; + if (c >= 0x80 || c == '"' || c == '{' || c == '[' || c == '}' || c == ']' || c == ':' || c == ',') { + return UNINITIALIZED; + } + if (c == 't') { + if (i + 4 > len || buf[i+1] != 'r' || buf[i+2] != 'u' || buf[i+3] != 'e') { return UNINITIALIZED; } + i += 4; + } else if (c == 'f') { + if (i + 5 > len || buf[i+1] != 'a' || buf[i+2] != 'l' || buf[i+3] != 's' || buf[i+4] != 'e') { return UNINITIALIZED; } + i += 5; + } else if (c == 'n') { + if (i + 4 > len || buf[i+1] != 'u' || buf[i+2] != 'l' || buf[i+3] != 'l') { return UNINITIALIZED; } + i += 4; + } else if (c == '-' || (c >= '0' && c <= '9')) { + if (c == '-') { + i++; + if (i == len) { return UNINITIALIZED; } + } + if (buf[i] == '0') { + i++; + } else if (buf[i] >= '1' && buf[i] <= '9') { + i++; + while (i < len && buf[i] >= '0' && buf[i] <= '9') { i++; } + } else { + return UNINITIALIZED; + } + if (i < len && buf[i] == '.') { + i++; + if (i == len || buf[i] < '0' || buf[i] > '9') { return UNINITIALIZED; } + while (i < len && buf[i] >= '0' && buf[i] <= '9') { i++; } + } + if (i < len && (buf[i] == 'e' || buf[i] == 'E')) { + i++; + if (i < len && (buf[i] == '+' || buf[i] == '-')) { i++; } + if (i == len || buf[i] < '0' || buf[i] > '9') { return UNINITIALIZED; } + while (i < len && buf[i] >= '0' && buf[i] <= '9') { i++; } + } + } else { + return UNINITIALIZED; + } + if (i < len && !is_json_ws(buf[i])) { return UNINITIALIZED; } + while (i < len) { + if (!is_json_ws(buf[i])) { return UNINITIALIZED; } + i++; + } + parser.buf = buf; + parser.len = len; + parser.structural_indexes[0] = uint32_t(atom); + parser.n_structural_indexes = 1; + parser.structural_indexes[1] = uint32_t(len); + parser.structural_indexes[2] = uint32_t(len); + parser.structural_indexes[3] = 0; + parser.next_structural_index = 0; + return SUCCESS; +} + simdjson_inline dom_parser_implementation::dom_parser_implementation() noexcept = default; simdjson_inline dom_parser_implementation::dom_parser_implementation(dom_parser_implementation &&other) noexcept = default; simdjson_inline dom_parser_implementation &dom_parser_implementation::operator=(dom_parser_implementation &&other) noexcept = default; @@ -4816,7 +5047,7 @@ class padded_memory_map { const char *data{nullptr}; size_t size{0}; #ifdef _WIN32 - // When the file ends near an allocation-granularity boundary, we use the + // When the file ends near a page boundary, we use the // placeholder API to append zero-filled padding pages. This pointer tracks // that region so the destructor can release it with VirtualFree. void *padding_view_{nullptr}; @@ -5774,12 +6005,13 @@ simdjson_inline padded_memory_map::~padded_memory_map() noexcept { // zero bytes after the file content, with no data copies. // // Strategy: -// 1. If rounding the file size up to the allocation granularity already -// exceeds file_size + SIMDJSON_PADDING, the OS page zero-fill provides -// the padding and we use a simple MapViewOfFile3 call. +// 1. If rounding the file size up to the page size already reaches +// file_size + SIMDJSON_PADDING, the OS page zero-fill provides the +// padding and we use a simple MapViewOfFile3 call. A view only maps the +// pages that hold the file, not its whole allocation granularity. // 2. Otherwise we reserve a contiguous placeholder region via VirtualAlloc2, -// split it at the granularity-aligned file boundary, map the file into -// the first part, and commit zero pages for the second part (padding). +// split it at the page-aligned file boundary, map the file into the +// first part, and commit zero pages for the second part (padding). simdjson_inline padded_memory_map::padded_memory_map(const char *filename) noexcept { HANDLE file_handle = ::CreateFileA( filename, GENERIC_READ, @@ -5816,8 +6048,8 @@ simdjson_inline padded_memory_map::padded_memory_map(const char *filename) noexc SYSTEM_INFO si; ::GetSystemInfo(&si); - const size_t granularity = static_cast(si.dwAllocationGranularity); - const size_t file_region = (size + granularity - 1) & ~(granularity - 1); + const size_t page_size = static_cast(si.dwPageSize); + const size_t file_region = (size + page_size - 1) & ~(page_size - 1); const size_t total_needed = size + simdjson::SIMDJSON_PADDING; if (file_region >= total_needed) { @@ -5836,7 +6068,7 @@ simdjson_inline padded_memory_map::padded_memory_map(const char *filename) noexc // to get a contiguous virtual address range spanning both the file mapping // and the zero-filled padding. const size_t padding_region = - ((total_needed - file_region) + granularity - 1) & ~(granularity - 1); + ((total_needed - file_region) + page_size - 1) & ~(page_size - 1); const size_t reserve_size = file_region + padding_region; // Reserve a contiguous placeholder. @@ -5856,9 +6088,10 @@ simdjson_inline padded_memory_map::padded_memory_map(const char *filename) noexc return; } - // Map the file into the first placeholder. + // Map the file into the first placeholder. The view may not extend past the + // end of the file; the rest of its last page reads as zero. PVOID file_view = ::MapViewOfFile3( - section, ::GetCurrentProcess(), placeholder, 0, file_region, + section, ::GetCurrentProcess(), placeholder, 0, size, MEM_REPLACE_PLACEHOLDER, PAGE_READONLY, NULL, 0); ::CloseHandle(section); if (file_view == NULL) { @@ -5872,7 +6105,7 @@ simdjson_inline padded_memory_map::padded_memory_map(const char *filename) noexc void *pad = static_cast(placeholder) + file_region; PVOID padding_ptr = ::VirtualAlloc2( ::GetCurrentProcess(), pad, padding_region, - MEM_REPLACE_PLACEHOLDER | MEM_COMMIT, PAGE_READONLY, NULL, 0); + MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, PAGE_READONLY, NULL, 0); if (padding_ptr == NULL) { ::UnmapViewOfFile(file_view); ::VirtualFree(pad, 0, MEM_RELEASE); @@ -6323,6 +6556,7 @@ inline constexpr bool enable_view @@ -6375,13 +6609,13 @@ class document { bool dump_raw_tape(std::ostream &os) const noexcept; /** @private Structural values. */ - std::unique_ptr tape{}; + internal::allocated_array tape{}; /** @private String values. * * Should be at least byte_capacity. */ - std::unique_ptr string_buf{}; + internal::allocated_array string_buf{}; /** @private Allocate memory to support * input JSON documents of up to len bytes. * @@ -6392,8 +6626,10 @@ class document { * can you use this function to increase * or lower the amount of allocated memory. * Passing zero clears the memory. + * + * The buffers come from allocator, or from new[] when it is nullptr. */ - error_code allocate(size_t len) noexcept; + error_code allocate(size_t len, const buffer_allocator *allocator = nullptr) noexcept; /** @private Capacity in bytes, in terms * of how many bytes of input JSON we can * support. @@ -7061,6 +7297,20 @@ class parser { */ simdjson_inline void set_max_capacity(size_t max_capacity) noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the structural indexes, and the tape and string buffer of the documents + * this parser allocates) through a buffer_allocator. nullptr, the default, + * uses new[]. The allocator must outlive the parser and those documents. + * + * Buffers that already exist keep the allocator that allocated them until + * they grow, so set the allocator before the first document or the first + * call to allocate(). A failed allocation makes the parser return MEMALLOC. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + #ifdef SIMDJSON_THREADS_ENABLED /** * The parser instance can use threads when they are available to speed up some @@ -7131,6 +7381,8 @@ class parser { /** Whether to store big integers as strings instead of returning BIGINT_ERROR */ bool _number_as_string{false}; + const buffer_allocator *_allocator{nullptr}; + /** * The loaded buffer (reused each time load() is called) */ @@ -7901,6 +8153,22 @@ class element { * @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not an array */ inline dom::array::iterator end() const noexcept(false); + + /** + * Iterate over each element in this array in reverse order. + * + * @return The beginning of the reverse iteration. + * @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not an array + */ + inline dom::array::reverse_iterator rbegin() const noexcept(false); + + /** + * Iterate over each element in this array in reverse order. + * + * @return The end of the reverse iteration. + * @exception simdjson_error(INCORRECT_TYPE) if the JSON element is not an array + */ + inline dom::array::reverse_iterator rend() const noexcept(false); #endif // SIMDJSON_EXCEPTIONS /** @@ -8131,6 +8399,8 @@ struct simdjson_result : public internal::simdjson_result_base std::string to_string(T x) { // in C++, to_string is standard: // http://www.cplusplus.com/reference/string/to_string/ Currently minify and // to_string are identical but in the future, they may differ. - simdjson::internal::string_builder<> sb; + simdjson_indeterminate simdjson::internal::string_builder<> sb; sb.append(x); std::string_view answer = sb.str(); return std::string(answer.data(), answer.size()); @@ -8799,7 +9069,7 @@ template std::string minify(simdjson_result x) { * */ template std::string prettify(T x, int indent_step = 4) { - simdjson::internal::string_builder sb(indent_step); + simdjson_indeterminate simdjson::internal::string_builder sb(indent_step); sb.append(x); std::string_view answer = sb.str(); return std::string(answer.data(), answer.size()); @@ -9655,9 +9925,7 @@ inline simdjson_result simdjson_result::at_pointer(std inline simdjson_result simdjson_result::at_path(std::string_view json_path) const noexcept { if (error()) { return error(); } - auto json_pointer = json_path_to_pointer_conversion(json_path); - if (json_pointer == "-1") { return INVALID_JSON_POINTER; } - return at_pointer(json_pointer); + return first.at_path(json_path); } inline simdjson_result> simdjson_result::at_path_with_wildcard(std::string_view json_path) const noexcept { @@ -9907,9 +10175,7 @@ inline simdjson_result simdjson_result::at_pointer(st } inline simdjson_result simdjson_result::at_path(std::string_view json_path) const noexcept { if (error()) { return error(); } - auto json_pointer = json_path_to_pointer_conversion(json_path); - if (json_pointer == "-1") { return INVALID_JSON_POINTER; } - return at_pointer(json_pointer); + return first.at_path(json_path); } inline simdjson_result> simdjson_result::at_path_with_wildcard(std::string_view json_path) const noexcept { if (error()) { @@ -10332,9 +10598,7 @@ simdjson_inline simdjson_result simdjson_result::at_ } simdjson_inline simdjson_result simdjson_result::at_path(const std::string_view json_path) const noexcept { if (error()) { return error(); } - auto json_pointer = json_path_to_pointer_conversion(json_path); - if (json_pointer == "-1") { return INVALID_JSON_POINTER; } - return at_pointer(json_pointer); + return first.at_path(json_path); } simdjson_inline simdjson_result> simdjson_result::at_path_with_wildcard(const std::string_view json_path) const noexcept { @@ -10400,6 +10664,14 @@ simdjson_inline dom::array::iterator simdjson_result::end() const if (error()) { throw simdjson_error(error()); } return first.end(); } +simdjson_inline dom::array::reverse_iterator simdjson_result::rbegin() const noexcept(false) { + if (error()) { throw simdjson_error(error()); } + return first.rbegin(); +} +simdjson_inline dom::array::reverse_iterator simdjson_result::rend() const noexcept(false) { + if (error()) { throw simdjson_error(error()); } + return first.rend(); +} #endif // SIMDJSON_EXCEPTIONS @@ -10674,6 +10946,12 @@ inline array::iterator element::begin() const noexcept(false) { inline array::iterator element::end() const noexcept(false) { return get().end(); } +inline array::reverse_iterator element::rbegin() const noexcept(false) { + return get().rbegin(); +} +inline array::reverse_iterator element::rend() const noexcept(false) { + return get().rend(); +} #endif // SIMDJSON_EXCEPTIONS @@ -11108,21 +11386,27 @@ simdjson_inline size_t parser::max_capacity() const noexcept { simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return implementation ? implementation->max_depth() : DEFAULT_MAX_DEPTH; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} simdjson_warn_unused inline error_code parser::allocate(size_t capacity, size_t max_depth) noexcept { // // Reallocate implementation if needed // - error_code err; - if (implementation) { - err = implementation->allocate(capacity, max_depth); - } else { - err = simdjson::get_active_implementation()->create_dom_parser_implementation(capacity, max_depth, implementation); - if (err) { implementation.reset(); } + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } - if (err) { return err; } - return SUCCESS; + implementation->allocator = _allocator; + return implementation->allocate(capacity, max_depth); } #ifndef SIMDJSON_DISABLE_DEPRECATED_API @@ -11151,7 +11435,7 @@ inline error_code parser::ensure_capacity(document& target_document, size_t desi if (desired_capacity > max_capacity()) { return error = CAPACITY; } - error_code err1 = target_document.capacity() < desired_capacity ? target_document.allocate(desired_capacity) : SUCCESS; + error_code err1 = target_document.capacity() < desired_capacity ? target_document.allocate(desired_capacity, _allocator) : SUCCESS; error_code err2 = capacity() < desired_capacity ? allocate(desired_capacity, max_depth()) : SUCCESS; if(err1 != SUCCESS) { return error = err1; } if(err2 != SUCCESS) { return error = err2; } @@ -11376,6 +11660,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); stage1_thread_parser.number_as_string(parser->number_as_string()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } @@ -11726,7 +12011,7 @@ inline size_t document::capacity() const noexcept { } simdjson_warn_unused -inline error_code document::allocate(size_t capacity) noexcept { +inline error_code document::allocate(size_t capacity, const buffer_allocator *allocator) noexcept { if (capacity == 0) { string_buf.reset(); tape.reset(); @@ -11752,9 +12037,7 @@ inline error_code document::allocate(size_t capacity) noexcept { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset( new (std::nothrow) uint8_t[string_capacity]); - tape.reset(new (std::nothrow) uint64_t[tape_capacity]); - if(!(string_buf && tape)) { + if(!string_buf.allocate(string_capacity, allocator) || !tape.allocate(tape_capacity, allocator)) { allocated_capacity = 0; string_buf.reset(); tape.reset(); @@ -11889,135 +12172,634 @@ inline bool document::dump_raw_tape(std::ostream &os) const noexcept { /* skipped duplicate #include "simdjson/dom/base.h" */ /* skipped duplicate #include "simdjson/dom/parser.h" */ /* skipped duplicate #include "simdjson/dom/serialization.h" */ -/* including simdjson/internal/jeaiii.h: #include "simdjson/internal/jeaiii.h" */ -/* begin file simdjson/internal/jeaiii.h */ -#ifndef SIMDJSON_INTERNAL_JEAIII_H -#define SIMDJSON_INTERNAL_JEAIII_H +/* including simdjson/internal/write_uint.h: #include "simdjson/internal/write_uint.h" */ +/* begin file simdjson/internal/write_uint.h */ +#ifndef SIMDJSON_INTERNAL_WRITE_UINT_H +#define SIMDJSON_INTERNAL_WRITE_UINT_H /* skipped duplicate #include "simdjson/base.h" */ +/* including simdjson/internal/four_digits.h: #include "simdjson/internal/four_digits.h" */ +/* begin file simdjson/internal/four_digits.h */ +#ifndef SIMDJSON_INTERNAL_FOUR_DIGITS_H +#define SIMDJSON_INTERNAL_FOUR_DIGITS_H + +namespace simdjson { +namespace internal { + +// The four decimal digits of every value in [0, 10000), leading zeros +// included: the digits of v are at data[4 * v]. Three padding bytes let +// a writer load four bytes starting at any of the four digits. +// A class template keeps a single copy of the table in a program +// without C++17 inline variables. +template struct four_digits { + static const char data[40004]; +}; + +template const char four_digits::data[40004] = + "00000001000200030004000500060007000800090010001100120013001400150016001700180019" + "00200021002200230024002500260027002800290030003100320033003400350036003700380039" + "00400041004200430044004500460047004800490050005100520053005400550056005700580059" + "00600061006200630064006500660067006800690070007100720073007400750076007700780079" + "00800081008200830084008500860087008800890090009100920093009400950096009700980099" + "01000101010201030104010501060107010801090110011101120113011401150116011701180119" + "01200121012201230124012501260127012801290130013101320133013401350136013701380139" + "01400141014201430144014501460147014801490150015101520153015401550156015701580159" + "01600161016201630164016501660167016801690170017101720173017401750176017701780179" + "01800181018201830184018501860187018801890190019101920193019401950196019701980199" + "02000201020202030204020502060207020802090210021102120213021402150216021702180219" + "02200221022202230224022502260227022802290230023102320233023402350236023702380239" + "02400241024202430244024502460247024802490250025102520253025402550256025702580259" + "02600261026202630264026502660267026802690270027102720273027402750276027702780279" + "02800281028202830284028502860287028802890290029102920293029402950296029702980299" + "03000301030203030304030503060307030803090310031103120313031403150316031703180319" + "03200321032203230324032503260327032803290330033103320333033403350336033703380339" + "03400341034203430344034503460347034803490350035103520353035403550356035703580359" + "03600361036203630364036503660367036803690370037103720373037403750376037703780379" + "03800381038203830384038503860387038803890390039103920393039403950396039703980399" + "04000401040204030404040504060407040804090410041104120413041404150416041704180419" + "04200421042204230424042504260427042804290430043104320433043404350436043704380439" + "04400441044204430444044504460447044804490450045104520453045404550456045704580459" + "04600461046204630464046504660467046804690470047104720473047404750476047704780479" + "04800481048204830484048504860487048804890490049104920493049404950496049704980499" + "05000501050205030504050505060507050805090510051105120513051405150516051705180519" + "05200521052205230524052505260527052805290530053105320533053405350536053705380539" + "05400541054205430544054505460547054805490550055105520553055405550556055705580559" + "05600561056205630564056505660567056805690570057105720573057405750576057705780579" + "05800581058205830584058505860587058805890590059105920593059405950596059705980599" + "06000601060206030604060506060607060806090610061106120613061406150616061706180619" + "06200621062206230624062506260627062806290630063106320633063406350636063706380639" + "06400641064206430644064506460647064806490650065106520653065406550656065706580659" + "06600661066206630664066506660667066806690670067106720673067406750676067706780679" + "06800681068206830684068506860687068806890690069106920693069406950696069706980699" + "07000701070207030704070507060707070807090710071107120713071407150716071707180719" + "07200721072207230724072507260727072807290730073107320733073407350736073707380739" + "07400741074207430744074507460747074807490750075107520753075407550756075707580759" + "07600761076207630764076507660767076807690770077107720773077407750776077707780779" + "07800781078207830784078507860787078807890790079107920793079407950796079707980799" + "08000801080208030804080508060807080808090810081108120813081408150816081708180819" + "08200821082208230824082508260827082808290830083108320833083408350836083708380839" + "08400841084208430844084508460847084808490850085108520853085408550856085708580859" + "08600861086208630864086508660867086808690870087108720873087408750876087708780879" + "08800881088208830884088508860887088808890890089108920893089408950896089708980899" + "09000901090209030904090509060907090809090910091109120913091409150916091709180919" + "09200921092209230924092509260927092809290930093109320933093409350936093709380939" + "09400941094209430944094509460947094809490950095109520953095409550956095709580959" + "09600961096209630964096509660967096809690970097109720973097409750976097709780979" + "09800981098209830984098509860987098809890990099109920993099409950996099709980999" + "10001001100210031004100510061007100810091010101110121013101410151016101710181019" + "10201021102210231024102510261027102810291030103110321033103410351036103710381039" + "10401041104210431044104510461047104810491050105110521053105410551056105710581059" + "10601061106210631064106510661067106810691070107110721073107410751076107710781079" + "10801081108210831084108510861087108810891090109110921093109410951096109710981099" + "11001101110211031104110511061107110811091110111111121113111411151116111711181119" + "11201121112211231124112511261127112811291130113111321133113411351136113711381139" + "11401141114211431144114511461147114811491150115111521153115411551156115711581159" + "11601161116211631164116511661167116811691170117111721173117411751176117711781179" + "11801181118211831184118511861187118811891190119111921193119411951196119711981199" + "12001201120212031204120512061207120812091210121112121213121412151216121712181219" + "12201221122212231224122512261227122812291230123112321233123412351236123712381239" + "12401241124212431244124512461247124812491250125112521253125412551256125712581259" + "12601261126212631264126512661267126812691270127112721273127412751276127712781279" + "12801281128212831284128512861287128812891290129112921293129412951296129712981299" + "13001301130213031304130513061307130813091310131113121313131413151316131713181319" + "13201321132213231324132513261327132813291330133113321333133413351336133713381339" + "13401341134213431344134513461347134813491350135113521353135413551356135713581359" + "13601361136213631364136513661367136813691370137113721373137413751376137713781379" + "13801381138213831384138513861387138813891390139113921393139413951396139713981399" + "14001401140214031404140514061407140814091410141114121413141414151416141714181419" + "14201421142214231424142514261427142814291430143114321433143414351436143714381439" + "14401441144214431444144514461447144814491450145114521453145414551456145714581459" + "14601461146214631464146514661467146814691470147114721473147414751476147714781479" + "14801481148214831484148514861487148814891490149114921493149414951496149714981499" + "15001501150215031504150515061507150815091510151115121513151415151516151715181519" + "15201521152215231524152515261527152815291530153115321533153415351536153715381539" + "15401541154215431544154515461547154815491550155115521553155415551556155715581559" + "15601561156215631564156515661567156815691570157115721573157415751576157715781579" + "15801581158215831584158515861587158815891590159115921593159415951596159715981599" + "16001601160216031604160516061607160816091610161116121613161416151616161716181619" + "16201621162216231624162516261627162816291630163116321633163416351636163716381639" + "16401641164216431644164516461647164816491650165116521653165416551656165716581659" + "16601661166216631664166516661667166816691670167116721673167416751676167716781679" + "16801681168216831684168516861687168816891690169116921693169416951696169716981699" + "17001701170217031704170517061707170817091710171117121713171417151716171717181719" + "17201721172217231724172517261727172817291730173117321733173417351736173717381739" + "17401741174217431744174517461747174817491750175117521753175417551756175717581759" + "17601761176217631764176517661767176817691770177117721773177417751776177717781779" + "17801781178217831784178517861787178817891790179117921793179417951796179717981799" + "18001801180218031804180518061807180818091810181118121813181418151816181718181819" + "18201821182218231824182518261827182818291830183118321833183418351836183718381839" + "18401841184218431844184518461847184818491850185118521853185418551856185718581859" + "18601861186218631864186518661867186818691870187118721873187418751876187718781879" + "18801881188218831884188518861887188818891890189118921893189418951896189718981899" + "19001901190219031904190519061907190819091910191119121913191419151916191719181919" + "19201921192219231924192519261927192819291930193119321933193419351936193719381939" + "19401941194219431944194519461947194819491950195119521953195419551956195719581959" + "19601961196219631964196519661967196819691970197119721973197419751976197719781979" + "19801981198219831984198519861987198819891990199119921993199419951996199719981999" + "20002001200220032004200520062007200820092010201120122013201420152016201720182019" + "20202021202220232024202520262027202820292030203120322033203420352036203720382039" + "20402041204220432044204520462047204820492050205120522053205420552056205720582059" + "20602061206220632064206520662067206820692070207120722073207420752076207720782079" + "20802081208220832084208520862087208820892090209120922093209420952096209720982099" + "21002101210221032104210521062107210821092110211121122113211421152116211721182119" + "21202121212221232124212521262127212821292130213121322133213421352136213721382139" + "21402141214221432144214521462147214821492150215121522153215421552156215721582159" + "21602161216221632164216521662167216821692170217121722173217421752176217721782179" + "21802181218221832184218521862187218821892190219121922193219421952196219721982199" + "22002201220222032204220522062207220822092210221122122213221422152216221722182219" + "22202221222222232224222522262227222822292230223122322233223422352236223722382239" + "22402241224222432244224522462247224822492250225122522253225422552256225722582259" + "22602261226222632264226522662267226822692270227122722273227422752276227722782279" + "22802281228222832284228522862287228822892290229122922293229422952296229722982299" + "23002301230223032304230523062307230823092310231123122313231423152316231723182319" + "23202321232223232324232523262327232823292330233123322333233423352336233723382339" + "23402341234223432344234523462347234823492350235123522353235423552356235723582359" + "23602361236223632364236523662367236823692370237123722373237423752376237723782379" + "23802381238223832384238523862387238823892390239123922393239423952396239723982399" + "24002401240224032404240524062407240824092410241124122413241424152416241724182419" + "24202421242224232424242524262427242824292430243124322433243424352436243724382439" + "24402441244224432444244524462447244824492450245124522453245424552456245724582459" + "24602461246224632464246524662467246824692470247124722473247424752476247724782479" + "24802481248224832484248524862487248824892490249124922493249424952496249724982499" + "25002501250225032504250525062507250825092510251125122513251425152516251725182519" + "25202521252225232524252525262527252825292530253125322533253425352536253725382539" + "25402541254225432544254525462547254825492550255125522553255425552556255725582559" + "25602561256225632564256525662567256825692570257125722573257425752576257725782579" + "25802581258225832584258525862587258825892590259125922593259425952596259725982599" + "26002601260226032604260526062607260826092610261126122613261426152616261726182619" + "26202621262226232624262526262627262826292630263126322633263426352636263726382639" + "26402641264226432644264526462647264826492650265126522653265426552656265726582659" + "26602661266226632664266526662667266826692670267126722673267426752676267726782679" + "26802681268226832684268526862687268826892690269126922693269426952696269726982699" + "27002701270227032704270527062707270827092710271127122713271427152716271727182719" + "27202721272227232724272527262727272827292730273127322733273427352736273727382739" + "27402741274227432744274527462747274827492750275127522753275427552756275727582759" + "27602761276227632764276527662767276827692770277127722773277427752776277727782779" + "27802781278227832784278527862787278827892790279127922793279427952796279727982799" + "28002801280228032804280528062807280828092810281128122813281428152816281728182819" + "28202821282228232824282528262827282828292830283128322833283428352836283728382839" + "28402841284228432844284528462847284828492850285128522853285428552856285728582859" + "28602861286228632864286528662867286828692870287128722873287428752876287728782879" + "28802881288228832884288528862887288828892890289128922893289428952896289728982899" + "29002901290229032904290529062907290829092910291129122913291429152916291729182919" + "29202921292229232924292529262927292829292930293129322933293429352936293729382939" + "29402941294229432944294529462947294829492950295129522953295429552956295729582959" + "29602961296229632964296529662967296829692970297129722973297429752976297729782979" + "29802981298229832984298529862987298829892990299129922993299429952996299729982999" + "30003001300230033004300530063007300830093010301130123013301430153016301730183019" + "30203021302230233024302530263027302830293030303130323033303430353036303730383039" + "30403041304230433044304530463047304830493050305130523053305430553056305730583059" + "30603061306230633064306530663067306830693070307130723073307430753076307730783079" + "30803081308230833084308530863087308830893090309130923093309430953096309730983099" + "31003101310231033104310531063107310831093110311131123113311431153116311731183119" + "31203121312231233124312531263127312831293130313131323133313431353136313731383139" + "31403141314231433144314531463147314831493150315131523153315431553156315731583159" + "31603161316231633164316531663167316831693170317131723173317431753176317731783179" + "31803181318231833184318531863187318831893190319131923193319431953196319731983199" + "32003201320232033204320532063207320832093210321132123213321432153216321732183219" + "32203221322232233224322532263227322832293230323132323233323432353236323732383239" + "32403241324232433244324532463247324832493250325132523253325432553256325732583259" + "32603261326232633264326532663267326832693270327132723273327432753276327732783279" + "32803281328232833284328532863287328832893290329132923293329432953296329732983299" + "33003301330233033304330533063307330833093310331133123313331433153316331733183319" + "33203321332233233324332533263327332833293330333133323333333433353336333733383339" + "33403341334233433344334533463347334833493350335133523353335433553356335733583359" + "33603361336233633364336533663367336833693370337133723373337433753376337733783379" + "33803381338233833384338533863387338833893390339133923393339433953396339733983399" + "34003401340234033404340534063407340834093410341134123413341434153416341734183419" + "34203421342234233424342534263427342834293430343134323433343434353436343734383439" + "34403441344234433444344534463447344834493450345134523453345434553456345734583459" + "34603461346234633464346534663467346834693470347134723473347434753476347734783479" + "34803481348234833484348534863487348834893490349134923493349434953496349734983499" + "35003501350235033504350535063507350835093510351135123513351435153516351735183519" + "35203521352235233524352535263527352835293530353135323533353435353536353735383539" + "35403541354235433544354535463547354835493550355135523553355435553556355735583559" + "35603561356235633564356535663567356835693570357135723573357435753576357735783579" + "35803581358235833584358535863587358835893590359135923593359435953596359735983599" + "36003601360236033604360536063607360836093610361136123613361436153616361736183619" + "36203621362236233624362536263627362836293630363136323633363436353636363736383639" + "36403641364236433644364536463647364836493650365136523653365436553656365736583659" + "36603661366236633664366536663667366836693670367136723673367436753676367736783679" + "36803681368236833684368536863687368836893690369136923693369436953696369736983699" + "37003701370237033704370537063707370837093710371137123713371437153716371737183719" + "37203721372237233724372537263727372837293730373137323733373437353736373737383739" + "37403741374237433744374537463747374837493750375137523753375437553756375737583759" + "37603761376237633764376537663767376837693770377137723773377437753776377737783779" + "37803781378237833784378537863787378837893790379137923793379437953796379737983799" + "38003801380238033804380538063807380838093810381138123813381438153816381738183819" + "38203821382238233824382538263827382838293830383138323833383438353836383738383839" + "38403841384238433844384538463847384838493850385138523853385438553856385738583859" + "38603861386238633864386538663867386838693870387138723873387438753876387738783879" + "38803881388238833884388538863887388838893890389138923893389438953896389738983899" + "39003901390239033904390539063907390839093910391139123913391439153916391739183919" + "39203921392239233924392539263927392839293930393139323933393439353936393739383939" + "39403941394239433944394539463947394839493950395139523953395439553956395739583959" + "39603961396239633964396539663967396839693970397139723973397439753976397739783979" + "39803981398239833984398539863987398839893990399139923993399439953996399739983999" + "40004001400240034004400540064007400840094010401140124013401440154016401740184019" + "40204021402240234024402540264027402840294030403140324033403440354036403740384039" + "40404041404240434044404540464047404840494050405140524053405440554056405740584059" + "40604061406240634064406540664067406840694070407140724073407440754076407740784079" + "40804081408240834084408540864087408840894090409140924093409440954096409740984099" + "41004101410241034104410541064107410841094110411141124113411441154116411741184119" + "41204121412241234124412541264127412841294130413141324133413441354136413741384139" + "41404141414241434144414541464147414841494150415141524153415441554156415741584159" + "41604161416241634164416541664167416841694170417141724173417441754176417741784179" + "41804181418241834184418541864187418841894190419141924193419441954196419741984199" + "42004201420242034204420542064207420842094210421142124213421442154216421742184219" + "42204221422242234224422542264227422842294230423142324233423442354236423742384239" + "42404241424242434244424542464247424842494250425142524253425442554256425742584259" + "42604261426242634264426542664267426842694270427142724273427442754276427742784279" + "42804281428242834284428542864287428842894290429142924293429442954296429742984299" + "43004301430243034304430543064307430843094310431143124313431443154316431743184319" + "43204321432243234324432543264327432843294330433143324333433443354336433743384339" + "43404341434243434344434543464347434843494350435143524353435443554356435743584359" + "43604361436243634364436543664367436843694370437143724373437443754376437743784379" + "43804381438243834384438543864387438843894390439143924393439443954396439743984399" + "44004401440244034404440544064407440844094410441144124413441444154416441744184419" + "44204421442244234424442544264427442844294430443144324433443444354436443744384439" + "44404441444244434444444544464447444844494450445144524453445444554456445744584459" + "44604461446244634464446544664467446844694470447144724473447444754476447744784479" + "44804481448244834484448544864487448844894490449144924493449444954496449744984499" + "45004501450245034504450545064507450845094510451145124513451445154516451745184519" + "45204521452245234524452545264527452845294530453145324533453445354536453745384539" + "45404541454245434544454545464547454845494550455145524553455445554556455745584559" + "45604561456245634564456545664567456845694570457145724573457445754576457745784579" + "45804581458245834584458545864587458845894590459145924593459445954596459745984599" + "46004601460246034604460546064607460846094610461146124613461446154616461746184619" + "46204621462246234624462546264627462846294630463146324633463446354636463746384639" + "46404641464246434644464546464647464846494650465146524653465446554656465746584659" + "46604661466246634664466546664667466846694670467146724673467446754676467746784679" + "46804681468246834684468546864687468846894690469146924693469446954696469746984699" + "47004701470247034704470547064707470847094710471147124713471447154716471747184719" + "47204721472247234724472547264727472847294730473147324733473447354736473747384739" + "47404741474247434744474547464747474847494750475147524753475447554756475747584759" + "47604761476247634764476547664767476847694770477147724773477447754776477747784779" + "47804781478247834784478547864787478847894790479147924793479447954796479747984799" + "48004801480248034804480548064807480848094810481148124813481448154816481748184819" + "48204821482248234824482548264827482848294830483148324833483448354836483748384839" + "48404841484248434844484548464847484848494850485148524853485448554856485748584859" + "48604861486248634864486548664867486848694870487148724873487448754876487748784879" + "48804881488248834884488548864887488848894890489148924893489448954896489748984899" + "49004901490249034904490549064907490849094910491149124913491449154916491749184919" + "49204921492249234924492549264927492849294930493149324933493449354936493749384939" + "49404941494249434944494549464947494849494950495149524953495449554956495749584959" + "49604961496249634964496549664967496849694970497149724973497449754976497749784979" + "49804981498249834984498549864987498849894990499149924993499449954996499749984999" + "50005001500250035004500550065007500850095010501150125013501450155016501750185019" + "50205021502250235024502550265027502850295030503150325033503450355036503750385039" + "50405041504250435044504550465047504850495050505150525053505450555056505750585059" + "50605061506250635064506550665067506850695070507150725073507450755076507750785079" + "50805081508250835084508550865087508850895090509150925093509450955096509750985099" + "51005101510251035104510551065107510851095110511151125113511451155116511751185119" + "51205121512251235124512551265127512851295130513151325133513451355136513751385139" + "51405141514251435144514551465147514851495150515151525153515451555156515751585159" + "51605161516251635164516551665167516851695170517151725173517451755176517751785179" + "51805181518251835184518551865187518851895190519151925193519451955196519751985199" + "52005201520252035204520552065207520852095210521152125213521452155216521752185219" + "52205221522252235224522552265227522852295230523152325233523452355236523752385239" + "52405241524252435244524552465247524852495250525152525253525452555256525752585259" + "52605261526252635264526552665267526852695270527152725273527452755276527752785279" + "52805281528252835284528552865287528852895290529152925293529452955296529752985299" + "53005301530253035304530553065307530853095310531153125313531453155316531753185319" + "53205321532253235324532553265327532853295330533153325333533453355336533753385339" + "53405341534253435344534553465347534853495350535153525353535453555356535753585359" + "53605361536253635364536553665367536853695370537153725373537453755376537753785379" + "53805381538253835384538553865387538853895390539153925393539453955396539753985399" + "54005401540254035404540554065407540854095410541154125413541454155416541754185419" + "54205421542254235424542554265427542854295430543154325433543454355436543754385439" + "54405441544254435444544554465447544854495450545154525453545454555456545754585459" + "54605461546254635464546554665467546854695470547154725473547454755476547754785479" + "54805481548254835484548554865487548854895490549154925493549454955496549754985499" + "55005501550255035504550555065507550855095510551155125513551455155516551755185519" + "55205521552255235524552555265527552855295530553155325533553455355536553755385539" + "55405541554255435544554555465547554855495550555155525553555455555556555755585559" + "55605561556255635564556555665567556855695570557155725573557455755576557755785579" + "55805581558255835584558555865587558855895590559155925593559455955596559755985599" + "56005601560256035604560556065607560856095610561156125613561456155616561756185619" + "56205621562256235624562556265627562856295630563156325633563456355636563756385639" + "56405641564256435644564556465647564856495650565156525653565456555656565756585659" + "56605661566256635664566556665667566856695670567156725673567456755676567756785679" + "56805681568256835684568556865687568856895690569156925693569456955696569756985699" + "57005701570257035704570557065707570857095710571157125713571457155716571757185719" + "57205721572257235724572557265727572857295730573157325733573457355736573757385739" + "57405741574257435744574557465747574857495750575157525753575457555756575757585759" + "57605761576257635764576557665767576857695770577157725773577457755776577757785779" + "57805781578257835784578557865787578857895790579157925793579457955796579757985799" + "58005801580258035804580558065807580858095810581158125813581458155816581758185819" + "58205821582258235824582558265827582858295830583158325833583458355836583758385839" + "58405841584258435844584558465847584858495850585158525853585458555856585758585859" + "58605861586258635864586558665867586858695870587158725873587458755876587758785879" + "58805881588258835884588558865887588858895890589158925893589458955896589758985899" + "59005901590259035904590559065907590859095910591159125913591459155916591759185919" + "59205921592259235924592559265927592859295930593159325933593459355936593759385939" + "59405941594259435944594559465947594859495950595159525953595459555956595759585959" + "59605961596259635964596559665967596859695970597159725973597459755976597759785979" + "59805981598259835984598559865987598859895990599159925993599459955996599759985999" + "60006001600260036004600560066007600860096010601160126013601460156016601760186019" + "60206021602260236024602560266027602860296030603160326033603460356036603760386039" + "60406041604260436044604560466047604860496050605160526053605460556056605760586059" + "60606061606260636064606560666067606860696070607160726073607460756076607760786079" + "60806081608260836084608560866087608860896090609160926093609460956096609760986099" + "61006101610261036104610561066107610861096110611161126113611461156116611761186119" + "61206121612261236124612561266127612861296130613161326133613461356136613761386139" + "61406141614261436144614561466147614861496150615161526153615461556156615761586159" + "61606161616261636164616561666167616861696170617161726173617461756176617761786179" + "61806181618261836184618561866187618861896190619161926193619461956196619761986199" + "62006201620262036204620562066207620862096210621162126213621462156216621762186219" + "62206221622262236224622562266227622862296230623162326233623462356236623762386239" + "62406241624262436244624562466247624862496250625162526253625462556256625762586259" + "62606261626262636264626562666267626862696270627162726273627462756276627762786279" + "62806281628262836284628562866287628862896290629162926293629462956296629762986299" + "63006301630263036304630563066307630863096310631163126313631463156316631763186319" + "63206321632263236324632563266327632863296330633163326333633463356336633763386339" + "63406341634263436344634563466347634863496350635163526353635463556356635763586359" + "63606361636263636364636563666367636863696370637163726373637463756376637763786379" + "63806381638263836384638563866387638863896390639163926393639463956396639763986399" + "64006401640264036404640564066407640864096410641164126413641464156416641764186419" + "64206421642264236424642564266427642864296430643164326433643464356436643764386439" + "64406441644264436444644564466447644864496450645164526453645464556456645764586459" + "64606461646264636464646564666467646864696470647164726473647464756476647764786479" + "64806481648264836484648564866487648864896490649164926493649464956496649764986499" + "65006501650265036504650565066507650865096510651165126513651465156516651765186519" + "65206521652265236524652565266527652865296530653165326533653465356536653765386539" + "65406541654265436544654565466547654865496550655165526553655465556556655765586559" + "65606561656265636564656565666567656865696570657165726573657465756576657765786579" + "65806581658265836584658565866587658865896590659165926593659465956596659765986599" + "66006601660266036604660566066607660866096610661166126613661466156616661766186619" + "66206621662266236624662566266627662866296630663166326633663466356636663766386639" + "66406641664266436644664566466647664866496650665166526653665466556656665766586659" + "66606661666266636664666566666667666866696670667166726673667466756676667766786679" + "66806681668266836684668566866687668866896690669166926693669466956696669766986699" + "67006701670267036704670567066707670867096710671167126713671467156716671767186719" + "67206721672267236724672567266727672867296730673167326733673467356736673767386739" + "67406741674267436744674567466747674867496750675167526753675467556756675767586759" + "67606761676267636764676567666767676867696770677167726773677467756776677767786779" + "67806781678267836784678567866787678867896790679167926793679467956796679767986799" + "68006801680268036804680568066807680868096810681168126813681468156816681768186819" + "68206821682268236824682568266827682868296830683168326833683468356836683768386839" + "68406841684268436844684568466847684868496850685168526853685468556856685768586859" + "68606861686268636864686568666867686868696870687168726873687468756876687768786879" + "68806881688268836884688568866887688868896890689168926893689468956896689768986899" + "69006901690269036904690569066907690869096910691169126913691469156916691769186919" + "69206921692269236924692569266927692869296930693169326933693469356936693769386939" + "69406941694269436944694569466947694869496950695169526953695469556956695769586959" + "69606961696269636964696569666967696869696970697169726973697469756976697769786979" + "69806981698269836984698569866987698869896990699169926993699469956996699769986999" + "70007001700270037004700570067007700870097010701170127013701470157016701770187019" + "70207021702270237024702570267027702870297030703170327033703470357036703770387039" + "70407041704270437044704570467047704870497050705170527053705470557056705770587059" + "70607061706270637064706570667067706870697070707170727073707470757076707770787079" + "70807081708270837084708570867087708870897090709170927093709470957096709770987099" + "71007101710271037104710571067107710871097110711171127113711471157116711771187119" + "71207121712271237124712571267127712871297130713171327133713471357136713771387139" + "71407141714271437144714571467147714871497150715171527153715471557156715771587159" + "71607161716271637164716571667167716871697170717171727173717471757176717771787179" + "71807181718271837184718571867187718871897190719171927193719471957196719771987199" + "72007201720272037204720572067207720872097210721172127213721472157216721772187219" + "72207221722272237224722572267227722872297230723172327233723472357236723772387239" + "72407241724272437244724572467247724872497250725172527253725472557256725772587259" + "72607261726272637264726572667267726872697270727172727273727472757276727772787279" + "72807281728272837284728572867287728872897290729172927293729472957296729772987299" + "73007301730273037304730573067307730873097310731173127313731473157316731773187319" + "73207321732273237324732573267327732873297330733173327333733473357336733773387339" + "73407341734273437344734573467347734873497350735173527353735473557356735773587359" + "73607361736273637364736573667367736873697370737173727373737473757376737773787379" + "73807381738273837384738573867387738873897390739173927393739473957396739773987399" + "74007401740274037404740574067407740874097410741174127413741474157416741774187419" + "74207421742274237424742574267427742874297430743174327433743474357436743774387439" + "74407441744274437444744574467447744874497450745174527453745474557456745774587459" + "74607461746274637464746574667467746874697470747174727473747474757476747774787479" + "74807481748274837484748574867487748874897490749174927493749474957496749774987499" + "75007501750275037504750575067507750875097510751175127513751475157516751775187519" + "75207521752275237524752575267527752875297530753175327533753475357536753775387539" + "75407541754275437544754575467547754875497550755175527553755475557556755775587559" + "75607561756275637564756575667567756875697570757175727573757475757576757775787579" + "75807581758275837584758575867587758875897590759175927593759475957596759775987599" + "76007601760276037604760576067607760876097610761176127613761476157616761776187619" + "76207621762276237624762576267627762876297630763176327633763476357636763776387639" + "76407641764276437644764576467647764876497650765176527653765476557656765776587659" + "76607661766276637664766576667667766876697670767176727673767476757676767776787679" + "76807681768276837684768576867687768876897690769176927693769476957696769776987699" + "77007701770277037704770577067707770877097710771177127713771477157716771777187719" + "77207721772277237724772577267727772877297730773177327733773477357736773777387739" + "77407741774277437744774577467747774877497750775177527753775477557756775777587759" + "77607761776277637764776577667767776877697770777177727773777477757776777777787779" + "77807781778277837784778577867787778877897790779177927793779477957796779777987799" + "78007801780278037804780578067807780878097810781178127813781478157816781778187819" + "78207821782278237824782578267827782878297830783178327833783478357836783778387839" + "78407841784278437844784578467847784878497850785178527853785478557856785778587859" + "78607861786278637864786578667867786878697870787178727873787478757876787778787879" + "78807881788278837884788578867887788878897890789178927893789478957896789778987899" + "79007901790279037904790579067907790879097910791179127913791479157916791779187919" + "79207921792279237924792579267927792879297930793179327933793479357936793779387939" + "79407941794279437944794579467947794879497950795179527953795479557956795779587959" + "79607961796279637964796579667967796879697970797179727973797479757976797779787979" + "79807981798279837984798579867987798879897990799179927993799479957996799779987999" + "80008001800280038004800580068007800880098010801180128013801480158016801780188019" + "80208021802280238024802580268027802880298030803180328033803480358036803780388039" + "80408041804280438044804580468047804880498050805180528053805480558056805780588059" + "80608061806280638064806580668067806880698070807180728073807480758076807780788079" + "80808081808280838084808580868087808880898090809180928093809480958096809780988099" + "81008101810281038104810581068107810881098110811181128113811481158116811781188119" + "81208121812281238124812581268127812881298130813181328133813481358136813781388139" + "81408141814281438144814581468147814881498150815181528153815481558156815781588159" + "81608161816281638164816581668167816881698170817181728173817481758176817781788179" + "81808181818281838184818581868187818881898190819181928193819481958196819781988199" + "82008201820282038204820582068207820882098210821182128213821482158216821782188219" + "82208221822282238224822582268227822882298230823182328233823482358236823782388239" + "82408241824282438244824582468247824882498250825182528253825482558256825782588259" + "82608261826282638264826582668267826882698270827182728273827482758276827782788279" + "82808281828282838284828582868287828882898290829182928293829482958296829782988299" + "83008301830283038304830583068307830883098310831183128313831483158316831783188319" + "83208321832283238324832583268327832883298330833183328333833483358336833783388339" + "83408341834283438344834583468347834883498350835183528353835483558356835783588359" + "83608361836283638364836583668367836883698370837183728373837483758376837783788379" + "83808381838283838384838583868387838883898390839183928393839483958396839783988399" + "84008401840284038404840584068407840884098410841184128413841484158416841784188419" + "84208421842284238424842584268427842884298430843184328433843484358436843784388439" + "84408441844284438444844584468447844884498450845184528453845484558456845784588459" + "84608461846284638464846584668467846884698470847184728473847484758476847784788479" + "84808481848284838484848584868487848884898490849184928493849484958496849784988499" + "85008501850285038504850585068507850885098510851185128513851485158516851785188519" + "85208521852285238524852585268527852885298530853185328533853485358536853785388539" + "85408541854285438544854585468547854885498550855185528553855485558556855785588559" + "85608561856285638564856585668567856885698570857185728573857485758576857785788579" + "85808581858285838584858585868587858885898590859185928593859485958596859785988599" + "86008601860286038604860586068607860886098610861186128613861486158616861786188619" + "86208621862286238624862586268627862886298630863186328633863486358636863786388639" + "86408641864286438644864586468647864886498650865186528653865486558656865786588659" + "86608661866286638664866586668667866886698670867186728673867486758676867786788679" + "86808681868286838684868586868687868886898690869186928693869486958696869786988699" + "87008701870287038704870587068707870887098710871187128713871487158716871787188719" + "87208721872287238724872587268727872887298730873187328733873487358736873787388739" + "87408741874287438744874587468747874887498750875187528753875487558756875787588759" + "87608761876287638764876587668767876887698770877187728773877487758776877787788779" + "87808781878287838784878587868787878887898790879187928793879487958796879787988799" + "88008801880288038804880588068807880888098810881188128813881488158816881788188819" + "88208821882288238824882588268827882888298830883188328833883488358836883788388839" + "88408841884288438844884588468847884888498850885188528853885488558856885788588859" + "88608861886288638864886588668867886888698870887188728873887488758876887788788879" + "88808881888288838884888588868887888888898890889188928893889488958896889788988899" + "89008901890289038904890589068907890889098910891189128913891489158916891789188919" + "89208921892289238924892589268927892889298930893189328933893489358936893789388939" + "89408941894289438944894589468947894889498950895189528953895489558956895789588959" + "89608961896289638964896589668967896889698970897189728973897489758976897789788979" + "89808981898289838984898589868987898889898990899189928993899489958996899789988999" + "90009001900290039004900590069007900890099010901190129013901490159016901790189019" + "90209021902290239024902590269027902890299030903190329033903490359036903790389039" + "90409041904290439044904590469047904890499050905190529053905490559056905790589059" + "90609061906290639064906590669067906890699070907190729073907490759076907790789079" + "90809081908290839084908590869087908890899090909190929093909490959096909790989099" + "91009101910291039104910591069107910891099110911191129113911491159116911791189119" + "91209121912291239124912591269127912891299130913191329133913491359136913791389139" + "91409141914291439144914591469147914891499150915191529153915491559156915791589159" + "91609161916291639164916591669167916891699170917191729173917491759176917791789179" + "91809181918291839184918591869187918891899190919191929193919491959196919791989199" + "92009201920292039204920592069207920892099210921192129213921492159216921792189219" + "92209221922292239224922592269227922892299230923192329233923492359236923792389239" + "92409241924292439244924592469247924892499250925192529253925492559256925792589259" + "92609261926292639264926592669267926892699270927192729273927492759276927792789279" + "92809281928292839284928592869287928892899290929192929293929492959296929792989299" + "93009301930293039304930593069307930893099310931193129313931493159316931793189319" + "93209321932293239324932593269327932893299330933193329333933493359336933793389339" + "93409341934293439344934593469347934893499350935193529353935493559356935793589359" + "93609361936293639364936593669367936893699370937193729373937493759376937793789379" + "93809381938293839384938593869387938893899390939193929393939493959396939793989399" + "94009401940294039404940594069407940894099410941194129413941494159416941794189419" + "94209421942294239424942594269427942894299430943194329433943494359436943794389439" + "94409441944294439444944594469447944894499450945194529453945494559456945794589459" + "94609461946294639464946594669467946894699470947194729473947494759476947794789479" + "94809481948294839484948594869487948894899490949194929493949494959496949794989499" + "95009501950295039504950595069507950895099510951195129513951495159516951795189519" + "95209521952295239524952595269527952895299530953195329533953495359536953795389539" + "95409541954295439544954595469547954895499550955195529553955495559556955795589559" + "95609561956295639564956595669567956895699570957195729573957495759576957795789579" + "95809581958295839584958595869587958895899590959195929593959495959596959795989599" + "96009601960296039604960596069607960896099610961196129613961496159616961796189619" + "96209621962296239624962596269627962896299630963196329633963496359636963796389639" + "96409641964296439644964596469647964896499650965196529653965496559656965796589659" + "96609661966296639664966596669667966896699670967196729673967496759676967796789679" + "96809681968296839684968596869687968896899690969196929693969496959696969796989699" + "97009701970297039704970597069707970897099710971197129713971497159716971797189719" + "97209721972297239724972597269727972897299730973197329733973497359736973797389739" + "97409741974297439744974597469747974897499750975197529753975497559756975797589759" + "97609761976297639764976597669767976897699770977197729773977497759776977797789779" + "97809781978297839784978597869787978897899790979197929793979497959796979797989799" + "98009801980298039804980598069807980898099810981198129813981498159816981798189819" + "98209821982298239824982598269827982898299830983198329833983498359836983798389839" + "98409841984298439844984598469847984898499850985198529853985498559856985798589859" + "98609861986298639864986598669867986898699870987198729873987498759876987798789879" + "98809881988298839884988598869887988898899890989198929893989498959896989798989899" + "99009901990299039904990599069907990899099910991199129913991499159916991799189919" + "99209921992299239924992599269927992899299930993199329933993499359936993799389939" + "99409941994299439944994599469947994899499950995199529953995499559956995799589959" + "99609961996299639964996599669967996899699970997199729973997499759976997799789979" + "99809981998299839984998599869987998899899990999199929993999499959996999799989999" + "000"; + +} // namespace internal +} // namespace simdjson + +#endif // SIMDJSON_INTERNAL_FOUR_DIGITS_H +/* end file simdjson/internal/four_digits.h */ #include #include namespace simdjson { namespace internal { -// Integer to decimal: James Edward Anhalt III's algorithm -static const char jeaiii_dd[201] = - "00010203040506070809101112131415161718192021222324252627282930313233343536373839" - "40414243444546474849505152535455565758596061626364656667686970717273747576777879" - "8081828384858687888990919293949596979899"; -static const char jeaiii_fd[201] = +// Integer to decimal. Values are cut into groups of four digits, and each +// group is copied from a table. The leading group has one to four digits: +// we count its leading zeros with comparisons and copy four bytes starting +// past them, so that the length of the group costs no branch. Up to three +// bytes past the last digit may be overwritten: callers reserve 20 bytes. + +// v < 10^4. Writes exactly four digits. +simdjson_really_inline void write_four_digits(char *b, uint32_t v) noexcept { + std::memcpy(b, &four_digits<>::data[4 * v], 4); +} + +// v < 10^4. Writes one to four digits. +simdjson_really_inline char *write_one_to_four_digits(char *b, uint32_t v) noexcept { + const uint32_t zeros = uint32_t(v < 10) + uint32_t(v < 100) + uint32_t(v < 1000); + std::memcpy(b, &four_digits<>::data[4 * v + zeros], 4); + return b + 4 - zeros; +} + +// The one or two digits of every value in [0, 100), at data[2 * v]: "d\0" +// below 10, "dd" otherwise. Copying two bytes from a fixed offset lets the +// digit count change only the returned pointer. Reading from four_digits at +// an offset that depends on v < 10 makes GCC branch, which mispredicts on a +// mix of 9- and 10-digit values. +template struct one_or_two_digits_table { + static const char data[201]; +}; + +template const char one_or_two_digits_table::data[201] = "0\0" "1\0" "2\0" "3\0" "4\0" "5\0" "6\0" "7\0" "8\0" "9\0" "10111213141516171819202122232425262728293031323334353637383940414243444546474849" "50515253545556575859606162636465666768697071727374757677787980818283848586878889" "90919293949596979899"; -simdjson_really_inline void jeaiii_write_dd(char *p, uint64_t k) noexcept { - std::memcpy(p, &jeaiii_dd[2 * k], 2); -} -simdjson_really_inline void jeaiii_write_fd(char *p, uint64_t k) noexcept { - std::memcpy(p, &jeaiii_fd[2 * k], 2); +// v < 100. Writes one or two digits. +simdjson_really_inline char *write_one_or_two_digits(char *b, uint32_t v) noexcept { + std::memcpy(b, &one_or_two_digits_table<>::data[2 * v], 2); + return b + 1 + uint32_t(v >= 10); } -// Caller guarantees n < 10^8. Writes 1 to 8 digits. -simdjson_really_inline char *jeaiii_lt1e8(char *b, uint32_t n) noexcept { - constexpr uint64_t mask24 = (uint64_t(1) << 24) - 1; - constexpr uint64_t mask32 = (uint64_t(1) << 32) - 1; - if (n < 100) { - jeaiii_write_fd(b, n); - return n < 10 ? b + 1 : b + 2; - } - if (n < 1000000) { - if (n < 10000) { - const uint32_t f0 = uint32_t(10 * (1 << 24) / 1e3 + 1) * n; - jeaiii_write_fd(b, f0 >> 24); - b -= n < 1000; - const uint32_t f2 = uint32_t(f0 & mask24) * 100; - jeaiii_write_dd(b + 2, f2 >> 24); - return b + 4; - } - const uint64_t f0 = uint64_t(10 * (1ull << 32) / 1e5 + 1) * n; - jeaiii_write_fd(b, f0 >> 32); - b -= n < 100000; - const uint64_t f2 = (f0 & mask32) * 100; - jeaiii_write_dd(b + 2, f2 >> 32); - const uint64_t f4 = (f2 & mask32) * 100; - jeaiii_write_dd(b + 4, f4 >> 32); - return b + 6; - } - const uint64_t f0 = uint64_t(10 * (1ull << 48) / 1e7 + 1) * n >> 16; - jeaiii_write_fd(b, f0 >> 32); - b -= n < 10000000; - const uint64_t f2 = (f0 & mask32) * 100; - jeaiii_write_dd(b + 2, f2 >> 32); - const uint64_t f4 = (f2 & mask32) * 100; - jeaiii_write_dd(b + 4, f4 >> 32); - const uint64_t f6 = (f4 & mask32) * 100; - jeaiii_write_dd(b + 6, f6 >> 32); - return b + 8; +// v < 10^8. Writes exactly eight digits. +simdjson_really_inline void write_eight_digits(char *b, uint32_t v) noexcept { + // (v * 109951163) >> 40 is v / 10^4 for v < 10^8. + const uint32_t high = uint32_t((uint64_t(v) * 109951163) >> 40); + write_four_digits(b, high); + write_four_digits(b + 4, v - high * 10000); } -// Caller guarantees z < 10^8. Always writes exactly 8 digits. -simdjson_really_inline char *jeaiii_8_digits(char *b, uint32_t z) noexcept { - constexpr uint64_t mask32 = (uint64_t(1) << 32) - 1; - const uint64_t f0 = (uint64_t((1ull << 48) / 1e6 + 1) * z >> 16) + 1; - jeaiii_write_dd(b, f0 >> 32); - const uint64_t f2 = (f0 & mask32) * 100; - jeaiii_write_dd(b + 2, f2 >> 32); - const uint64_t f4 = (f2 & mask32) * 100; - jeaiii_write_dd(b + 4, f4 >> 32); - const uint64_t f6 = (f4 & mask32) * 100; - jeaiii_write_dd(b + 6, f6 >> 32); - return b + 8; +// n < 10^8. Writes one to eight digits. +simdjson_really_inline char *write_below_1e8(char *b, uint32_t n) noexcept { + if (n < 100) { + return write_one_or_two_digits(b, n); + } + if (n < 10000) { + return write_one_to_four_digits(b, n); + } + const uint32_t high = uint32_t((uint64_t(n) * 109951163) >> 40); + b = write_one_to_four_digits(b, high); + write_four_digits(b, n - high * 10000); + return b + 4; } -// Caller guarantees 10^8 <= n < 2^32. Writes 9 or 10 digits. -simdjson_really_inline char *jeaiii_9_or_10(char *b, uint64_t n) noexcept { - constexpr uint64_t mask57 = (uint64_t(1) << 57) - 1; - const uint64_t f0 = uint64_t(10 * (1ull << 57) / 1e9 + 1) * n; - jeaiii_write_fd(b, f0 >> 57); - b -= n < 1000000000; - const uint64_t f2 = (f0 & mask57) * 100; - jeaiii_write_dd(b + 2, f2 >> 57); - const uint64_t f4 = (f2 & mask57) * 100; - jeaiii_write_dd(b + 4, f4 >> 57); - const uint64_t f6 = (f4 & mask57) * 100; - jeaiii_write_dd(b + 6, f6 >> 57); - const uint64_t f8 = (f6 & mask57) * 100; - jeaiii_write_dd(b + 8, f8 >> 57); - return b + 10; -} - -simdjson_really_inline char *write_uint_jeaiii(char *b, uint64_t n) noexcept { +// Writes the decimal digits of n at b and returns a pointer past the last +// digit. +simdjson_really_inline char *write_uint(char *b, uint64_t n) noexcept { if (n < 100000000) { - return jeaiii_lt1e8(b, uint32_t(n)); - } - if (n < (uint64_t(1) << 32)) { - return jeaiii_9_or_10(b, n); - } - // At least 10 digits: the low 8 digits, and 2 to 12 digits above them. - const uint32_t z = uint32_t(n % 100000000); - uint64_t u = n / 100000000; - if (u < 100000000) { - // u has 2 to 8 digits (if u < 10, n would be below 2^32). - b = jeaiii_lt1e8(b, uint32_t(u)); - } else if (u < (uint64_t(1) << 32)) { - b = jeaiii_9_or_10(b, u); - } else { - // u has 11 or 12 digits: split off 8 more. - const uint32_t y = uint32_t(u % 100000000); - u /= 100000000; - b = jeaiii_lt1e8(b, uint32_t(u)); // 3 or 4 digits - b = jeaiii_8_digits(b, y); - } - return jeaiii_8_digits(b, z); + return write_below_1e8(b, uint32_t(n)); + } + // At least 9 digits: the low 8 digits, and 1 to 12 digits above them. + const uint64_t high = n / 100000000; + const uint32_t low = uint32_t(n - high * 100000000); + if (high < 100) { + // 9 or 10 digits, the most common long integers (32-bit values). + b = write_one_or_two_digits(b, uint32_t(high)); + } else if (high < 100000000) { + b = write_below_1e8(b, uint32_t(high)); + } else { + // 17 to 20 digits: the top has 1 to 4 digits. + const uint64_t top = high / 100000000; + b = write_one_to_four_digits(b, uint32_t(top)); + write_eight_digits(b, uint32_t(high - top * 100000000)); + b += 8; + } + write_eight_digits(b, low); + return b + 8; } } // namespace internal } // namespace simdjson -#endif // SIMDJSON_INTERNAL_JEAIII_H -/* end file simdjson/internal/jeaiii.h */ +#endif // SIMDJSON_INTERNAL_WRITE_UINT_H +/* end file simdjson/internal/write_uint.h */ /* including simdjson/internal/json_escape.h: #include "simdjson/internal/json_escape.h" */ /* begin file simdjson/internal/json_escape.h */ #ifndef SIMDJSON_INTERNAL_JSON_ESCAPE_H @@ -12872,16 +13654,15 @@ namespace internal { template simdjson_inline void base_formatter::number(uint64_t x) { - // write_uint_jeaiii may store one byte before its output pointer. - char number_buffer[24]; - chars(number_buffer + 1, write_uint_jeaiii(number_buffer + 1, x)); + simdjson_indeterminate char number_buffer[24]; + chars(number_buffer + 1, write_uint(number_buffer + 1, x)); } template simdjson_inline void base_formatter::number(int64_t x) { - char number_buffer[24]; + simdjson_indeterminate char number_buffer[24]; // 0 - uint64_t(x) is the magnitude, also for INT64_MIN. - char *end = write_uint_jeaiii(number_buffer + 1, x < 0 ? 0 - uint64_t(x) : uint64_t(x)); + char *end = write_uint(number_buffer + 1, x < 0 ? 0 - uint64_t(x) : uint64_t(x)); number_buffer[0] = '-'; chars(number_buffer + (x >= 0), end); } @@ -12906,7 +13687,7 @@ simdjson_inline void base_formatter::number(double x) { // Must be to_chars_buffer_size (40): only ~24 chars are emitted, but // to_chars over-writes with fixed-size 16/17-byte copies for inlining. - char number_buffer[simdjson::internal::to_chars_buffer_size]; + simdjson_indeterminate char number_buffer[simdjson::internal::to_chars_buffer_size]; // Currently, passing the nullptr to the second argument is // safe because our implementation does not check the second // argument. @@ -13896,7 +14677,7 @@ inline size_t structure_analyzer::estimate_number_length(double d) const { // (e.g. 0.1 becomes "0.10000000000000001", 19 chars, vs the emitted "0.1"), // which misaligns double columns in table formatting the same way escaped // control characters did before #2929. - char buf[simdjson::internal::to_chars_buffer_size]; + simdjson_indeterminate char buf[simdjson::internal::to_chars_buffer_size]; char *end = simdjson::internal::to_chars(buf, buf + sizeof(buf), d); return static_cast(end - buf); } @@ -16122,6 +16903,33 @@ extern SIMDJSON_DLLIMPORTEXPORT const uint64_t power_of_five_128[651*2]; #endif // SIMDJSON_INTERNAL_NUMBERPARSING_TABLES_H /* end file simdjson/internal/numberparsing_tables.h */ +/* including simdjson/internal/numberparsing.h: #include "simdjson/internal/numberparsing.h" */ +/* begin file simdjson/internal/numberparsing.h */ +#ifndef SIMDJSON_INTERNAL_NUMBERPARSING_H +#define SIMDJSON_INTERNAL_NUMBERPARSING_H + +/* skipped duplicate #include "simdjson/base.h" */ + +namespace simdjson { +namespace internal { + +/** + * The value of the eight ASCII digits in val, the first digit in the lowest + * byte (little-endian). Only the low four bits of each byte count, so zero + * bytes act as leading zeros. The scalar parse_eight_digits_unrolled. + * credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ + */ +simdjson_inline uint32_t parse_eight_digits_swar(uint64_t val) { + val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; + val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; + return static_cast((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); +} + +} // namespace internal +} // namespace simdjson + +#endif // SIMDJSON_INTERNAL_NUMBERPARSING_H +/* end file simdjson/internal/numberparsing.h */ /* including simdjson/internal/simdprune_tables.h: #include "simdjson/internal/simdprune_tables.h" */ /* begin file simdjson/internal/simdprune_tables.h */ #ifndef SIMDJSON_INTERNAL_SIMDPRUNE_TABLES_H @@ -16146,6 +16954,56 @@ extern SIMDJSON_DLLIMPORTEXPORT const uint64_t thintable_epi8[256]; #endif // SIMDJSON_INTERNAL_SIMDPRUNE_TABLES_H /* end file simdjson/internal/simdprune_tables.h */ +/* including simdjson/internal/partial_load.h: #include "simdjson/internal/partial_load.h" */ +/* begin file simdjson/internal/partial_load.h */ +#ifndef SIMDJSON_INTERNAL_PARTIAL_LOAD_H +#define SIMDJSON_INTERNAL_PARTIAL_LOAD_H + +/* skipped duplicate #include "simdjson/base.h" */ + +#include +#include + +namespace simdjson { +namespace internal { + +// shift_tail_mask + 16 - n holds the byte indexes that move the last n bytes +// of a 16-byte vector to its front, followed by indexes with the high bit set. +alignas(16) static const uint8_t shift_tail_mask[32] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 +}; + +// Loads the n < 16 bytes at ptr, and only those, into two little-endian +// words. The other bytes are set to fill. +simdjson_inline void load_small_words(const uint8_t *ptr, size_t n, uint8_t fill, uint64_t &lo, uint64_t &hi) { + const uint64_t fills = 0x0101010101010101 * fill; + lo = fills; + hi = fills; + if (n >= 8) { + std::memcpy(&lo, ptr, 8); + if (n > 8) { + // The 8 bytes ending at ptr + n overlap lo: keep their last n - 8. + uint64_t tail; + std::memcpy(&tail, ptr + n - 8, 8); + hi = (tail >> (8 * (16 - n))) | (fills << (8 * (n - 8))); + } + } else if (n >= 4) { + uint32_t first, last; + std::memcpy(&first, ptr, 4); + std::memcpy(&last, ptr + n - 4, 4); + lo = first | (uint64_t(last) << (8 * (n - 4))) | (fills << (8 * n)); + } else if (n > 0) { + lo = ptr[0] | (uint64_t(ptr[n / 2]) << (8 * (n / 2))) | (uint64_t(ptr[n - 1]) << (8 * (n - 1))) + | (fills << (8 * n)); + } +} + +} // namespace internal +} // namespace simdjson + +#endif // SIMDJSON_INTERNAL_PARTIAL_LOAD_H +/* end file simdjson/internal/partial_load.h */ #endif // SIMDJSON_GENERIC_DEPENDENCIES_H /* end file simdjson/generic/dependencies.h */ @@ -16743,6 +17601,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -16757,14 +17616,11 @@ namespace arm64 { namespace numberparsing { // we don't have SSE, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -16808,6 +17664,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -16956,6 +17813,26 @@ namespace { static simdjson_inline uint8x16_t splat(uint8_t _value) { return vmovq_n_u8(_value); } static simdjson_inline uint8x16_t zero() { return vdupq_n_u8(0); } static simdjson_inline uint8x16_t load(const uint8_t* values) { return vld1q_u8(values); } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline uint8x16_t load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const uint8x16_t window = vld1q_u8(ptr + n - 16); + const uint8x16_t shuffle = vld1q_u8(internal::shift_tail_mask + 16 - n); + // vqtbl1q_u8 zeroes the bytes whose index is out of range. + const uint8x16_t filler = vandq_u8(vcgeq_u8(shuffle, vdupq_n_u8(16)), vdupq_n_u8(fill)); + return vorrq_u8(vqtbl1q_u8(window, shuffle), filler); + } +#if SIMDJSON_IS_BIG_ENDIAN + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return vld1q_u8(block); +#else + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return vcombine_u8(vcreate_u8(lo), vcreate_u8(hi)); +#endif + } simdjson_inline simd8(const uint8x16_t _value) : base_u8(_value) {} // Zero constructor @@ -17747,10 +18624,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -17798,8 +18671,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -17993,6 +18866,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -18584,6 +19458,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -18637,19 +19520,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -18657,7 +19558,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -19038,10 +19941,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -19088,10 +19989,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -19143,10 +20042,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -19188,10 +20085,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -19958,6 +20853,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/fallback/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -19973,14 +20869,11 @@ namespace simdjson { namespace fallback { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; - memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + std::memcpy(&val, chars, sizeof(uint64_t)); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -20406,10 +21299,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -20457,8 +21346,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -20652,6 +21541,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -21243,6 +22133,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -21296,19 +22195,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -21316,7 +22233,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -21697,10 +22616,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -21747,10 +22664,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -21802,10 +22717,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -21847,10 +22760,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -22750,6 +23661,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/haswell/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/haswell/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -22972,6 +23884,26 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + const __m128i lo = n >= 16 ? _mm_loadu_si128(reinterpret_cast(ptr)) : load_partial_16(ptr, n, begin, fill); + const __m128i hi = n > 16 ? load_partial_16(ptr + 16, n - 16, begin, fill) : _mm_set1_epi8(char(fill)); + return _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -23535,10 +24467,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -23586,8 +24514,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -23781,6 +24709,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -24372,6 +25301,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -24425,19 +25363,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -24445,7 +25401,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -24826,10 +25784,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -24876,10 +25832,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -24931,10 +25885,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -24976,10 +25928,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -26040,6 +26990,12 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 64 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + // Masked-off bytes are not read, so they cannot fault. + return _mm512_mask_loadu_epi8(_mm512_set1_epi8(char(fill)), (uint64_t(1) << n) - 1, ptr); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m512i _value) : base8_numeric(_value) {} // Splat constructor @@ -26660,10 +27616,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -26711,8 +27663,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -26906,6 +27858,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -27497,6 +28450,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -27550,19 +28512,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -27570,7 +28550,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -27951,10 +28933,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -28001,10 +28981,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -28056,10 +29034,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -28101,10 +29077,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -28924,6 +29898,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/ppc64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/ppc64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -28939,7 +29914,6 @@ namespace ppc64 { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; @@ -28951,9 +29925,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars val = bswap64(val); #endif #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -29279,6 +30251,14 @@ template <> struct simd8 : base8_numeric { // Unsigned bytes template <> struct simd8 : base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} @@ -29906,10 +30886,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -29957,8 +30933,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -30152,6 +31128,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -30743,6 +31720,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -30796,19 +31782,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -30816,7 +31820,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -31197,10 +32203,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -31247,10 +32251,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -31302,10 +32304,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -31347,10 +32347,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -32294,6 +33292,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -32488,6 +33487,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -32713,6 +33730,7 @@ simdjson_inline long long int count_ones(uint64_t input_num) { /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -32907,6 +33925,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -33457,10 +34493,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -33508,8 +34540,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -33703,6 +34735,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -34294,6 +35327,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -34347,19 +35389,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -34367,7 +35427,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -34748,10 +35810,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -34798,10 +35858,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -34853,10 +35911,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -34898,10 +35954,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -35692,6 +36746,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lasx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lasx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -35701,14 +36756,11 @@ namespace lasx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -35960,6 +37012,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[32]; + std::memset(block, fill, 32); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -36532,10 +37592,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -36583,8 +37639,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -36778,6 +37834,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -37369,6 +38426,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -37422,19 +38488,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -37442,7 +38526,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -37823,10 +38909,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -37873,10 +38957,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -37928,10 +39010,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -37973,10 +39053,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -38752,6 +39830,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lsx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lsx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -38761,14 +39840,11 @@ namespace lsx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -38993,6 +40069,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -39577,10 +40661,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -39628,8 +40708,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -39823,6 +40903,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -40414,6 +41495,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -40467,19 +41557,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -40487,7 +41595,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -40868,10 +41978,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -40918,10 +42026,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -40973,10 +42079,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -41018,10 +42122,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -41900,6 +43002,14 @@ namespace simd { simdjson_inline simd8() : simd8(zero()) {} simdjson_inline simd8(const uint8_t values[VL8]) : simd8(load(values)) {} simdjson_inline simd8(uint8_t _value) : simd8(splat(_value)) {} + // The n < VL8 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[VL8]; + std::memset(block, fill, VL8); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8(simd8 mask) : value(__riscv_vmerge_vxm_u8m1(zero(), -1, (vbool_t)mask, VL8)) {} simdjson_inline operator const vuint8_t&() const { return this->value; } @@ -42236,6 +43346,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/rvv-vls/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -42251,7 +43362,6 @@ namespace simdjson { namespace rvv_vls { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; @@ -42260,9 +43370,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { #else val = __riscv_vmv_x(__riscv_vreinterpret_u64m1(__riscv_vlmul_ext_u8m1(__riscv_vle8_v_u8mf2((uint8_t*)chars, 8)))); #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -42656,10 +43764,6 @@ class dom_parser_implementation final : public internal::dom_parser_implementati std::unique_ptr open_containers{}; /** Whether each open container is a [ or { */ std::unique_ptr is_array{}; - /** Buffer passed to stage 1 */ - const uint8_t *buf{}; - /** Length passed to stage 1 */ - size_t len{0}; /** Document passed to stage 2 */ dom::document *doc{}; @@ -42707,8 +43811,8 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s // implementation keeps its previous buffer and capacity. Otherwise a parser // that still believes it has room skips reallocation and stage 1 rejects // every document with CAPACITY. - std::unique_ptr new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); - if (!new_structural_indexes) { return MEMALLOC; } + internal::allocated_array new_structural_indexes; + if (!new_structural_indexes.allocate(max_structures, allocator)) { return MEMALLOC; } structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -42902,6 +44006,7 @@ struct implementation_simdjson_result_base { /* amalgamation skipped (editor-only): #include "simdjson/generic/jsoncharutils.h" */ /* amalgamation skipped (editor-only): #include "simdjson/generic/atomparsing.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -43493,6 +44598,15 @@ simdjson_inline uint32_t parse_four_digits_unrolled(const uint8_t *chars) { return (((val & 0x00FF00FF) * 0x00640001) >> 16) & 0xFFFF; } +// The test of is_made_of_four_digits_fast on eight bytes, kept as a mask: sets +// the high bit of every byte that is not '0'..'9'. Carries and borrows only move +// upwards, so the bytes up to and including the first non-digit are always right, +// which is all trailing_zeroes() looks at. Little-endian: guarded by +// SIMDJSON_SWAR_NUMBER_PARSING. +simdjson_inline uint64_t mark_non_digits(uint64_t val) { + return ((val + 0x4646464646464646) | (val - 0x3030303030303030)) & 0x8080808080808080; +} + template SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later simdjson_inline bool parse_digit(const uint8_t c, I &i) { @@ -43546,19 +44660,37 @@ simdjson_inline void parse_float_integer_digits(const uint8_t *&p, uint64_t &i, while (parse_digit(*p, i)) { p++; } } -SIMDJSON_NO_SANITIZE_UNDEFINED -simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { +// Consumes a run of digits and returns its value. +// +// Prior related work: jsonifier finds the end of the digits with a SWAR mask +// and a trailing-zero count too, and converts eight digits at a time +// (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). +SIMDJSON_NO_SANITIZE_UNDEFINED // We deliberately allow overflow here and check later +simdjson_inline uint64_t parse_integer_digits(const uint8_t *&p) { + uint64_t i = 0; + #ifdef SIMDJSON_SWAR_NUMBER_PARSING #if SIMDJSON_SWAR_NUMBER_PARSING - // Identifiers, timestamps and counters often have eight digits or more. - // Prior related work: jsonifier parses integers as eight-digit SWAR words - // (str_to_i.hpp, https://github.com/nihilai-collective/Jsonifier). This - // takes one such word with parse_eight_digits_unrolled, the routine - // simdjson uses for long fractions. - if (is_made_of_eight_digits_fast(p)) { - i = i * 100000000 + parse_eight_digits_unrolled(p); - p += 8; + // Reads up to 7 bytes beyond the digits, which SIMDJSON_PADDING covers. + static_assert(7 <= SIMDJSON_PADDING, "SIMDJSON_PADDING must be bigger than 7"); + uint64_t val; + std::memcpy(&val, p, 8); + + // Up to 7 digits: the common case. Their count changes from one number to + // the next, so instead of looping, every count takes the same instructions. + const uint64_t non_digits = mark_non_digits(val); + if (non_digits != 0) { + const size_t digit_count = size_t(trailing_zeroes(non_digits)) / 8; + if (digit_count == 0) { return 0; } + p += digit_count; + + // Move the digits to the top; the zero bytes shifted in are leading zeros. + return internal::parse_eight_digits_swar(val << (64 - 8 * digit_count)); } + + i = parse_eight_digits_unrolled(p); + p += 8; + const uint8_t *const swar_end = p + 8; while (p < swar_end && is_made_of_four_digits_fast(p)) { i = i * 10000 + parse_four_digits_unrolled(p); @@ -43566,7 +44698,9 @@ simdjson_inline void parse_integer_digits(const uint8_t *&p, uint64_t &i) { } #endif // SIMDJSON_SWAR_NUMBER_PARSING #endif // #ifdef SIMDJSON_SWAR_NUMBER_PARSING + while (parse_digit(*p, i)) { p++; } + return i; } simdjson_warn_unused simdjson_inline error_code parse_decimal_after_separator(simdjson_unused const uint8_t *const src, const uint8_t *&p, uint64_t &i, int64_t &exponent) { @@ -43947,10 +45081,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned(const u // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -43997,10 +45129,8 @@ simdjson_unused simdjson_inline simdjson_result parse_unsigned_in_stri // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -44052,10 +45182,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer(const uin // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = p; - uint64_t i = 0; - parse_integer_digits(p, i); + uint64_t i = parse_integer_digits(p); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -44097,10 +45225,8 @@ simdjson_unused simdjson_inline simdjson_result parse_integer_in_string // // Parse the integer part. // - // PERF NOTE: we don't use is_made_of_eight_digits_fast because large integers like 123456789 are rare const uint8_t *const start_digits = src; - uint64_t i = 0; - parse_integer_digits(src, i); + uint64_t i = parse_integer_digits(src); // If there were no digits, or if the integer starts with 0 and has more than one digit, it's an error. // Optimization note: size_t is expected to be unsigned. @@ -45077,16 +46203,34 @@ consteval std::vector json_key_names(std::meta::info entity) { return names; } +#if !defined(__cpp_exceptions) +// Without exceptions, consteval code cannot throw std::meta::exception. It +// calls one of these functions instead: they are not constexpr, so the +// constant evaluation fails and the compiler error names the function. +inline void flatten_requires_a_member_that_is_not_a_reference() {} +inline void flatten_requires_a_member_of_class_type() {} +inline void transparent_requires_exactly_one_data_member() {} +inline void flatten_requires_a_member_deserialized_member_by_member() {} +#endif + // The structure type of a member annotated with flatten. consteval std::meta::info flattened_type(std::meta::info mem) { if (std::meta::is_reference_type(std::meta::type_of(mem))) { // A reference member could refer back to the enclosing structure: the // flattening would never terminate. +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member that is not a reference", mem); +#else + flatten_requires_a_member_that_is_not_a_reference(); +#endif } std::meta::info type = std::meta::remove_cvref(std::meta::type_of(mem)); if (!std::meta::is_class_type(type)) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member of class type", mem); +#else + flatten_requires_a_member_of_class_type(); +#endif } return type; } @@ -45099,7 +46243,11 @@ consteval std::meta::info transparent_member(std::meta::info type) { if (!has_annotation(mem, ^^skip_tag)) { members.push_back(mem); } } if (members.size() != 1) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::transparent requires exactly one data member (not counting skipped members)", type); +#else + transparent_requires_exactly_one_data_member(); +#endif } return members[0]; } @@ -45117,7 +46265,7 @@ consteval const char* get_json_key_name() { #endif // SIMDJSON_STATIC_REFLECTION #endif // SIMDJSON_ANNOTATIONS_H /* end file simdjson/annotations.h */ -/* skipped duplicate #include "simdjson/internal/jeaiii.h" */ +/* skipped duplicate #include "simdjson/internal/write_uint.h" */ /* skipped duplicate #include "simdjson/internal/json_escape.h" */ #endif // SIMDJSON_GENERIC_BUILDER_DEPENDENCIES_H @@ -45351,6 +46499,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -45365,14 +46514,11 @@ namespace arm64 { namespace numberparsing { // we don't have SSE, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -45416,6 +46562,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -45564,6 +46711,26 @@ namespace { static simdjson_inline uint8x16_t splat(uint8_t _value) { return vmovq_n_u8(_value); } static simdjson_inline uint8x16_t zero() { return vdupq_n_u8(0); } static simdjson_inline uint8x16_t load(const uint8_t* values) { return vld1q_u8(values); } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline uint8x16_t load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const uint8x16_t window = vld1q_u8(ptr + n - 16); + const uint8x16_t shuffle = vld1q_u8(internal::shift_tail_mask + 16 - n); + // vqtbl1q_u8 zeroes the bytes whose index is out of range. + const uint8x16_t filler = vandq_u8(vcgeq_u8(shuffle, vdupq_n_u8(16)), vdupq_n_u8(fill)); + return vorrq_u8(vqtbl1q_u8(window, shuffle), filler); + } +#if SIMDJSON_IS_BIG_ENDIAN + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return vld1q_u8(block); +#else + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return vcombine_u8(vcreate_u8(lo), vcreate_u8(hi)); +#endif + } simdjson_inline simd8(const uint8x16_t _value) : base_u8(_value) {} // Zero constructor @@ -46042,6 +47209,36 @@ namespace builder { using simdjson::internal::escape_best::write_string_escaped; +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +/** + * A contiguous, sized range of integers that string_builder serializes as a + * JSON array of numbers in one pass. Booleans and character types are excluded, + * and so are integers wider than 64 bits. In C++26, std::optional is a + * contiguous range: it is excluded so that the optional overload is chosen. + */ +template +concept integer_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !concepts::optional_type && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; + +namespace internal { +// Elements must be class types (std::string, std::string_view, ...): a +// range of const char * would pay strlen twice. +template +concept contiguous_string_range = + std::ranges::contiguous_range && !concepts::optional_type && + !std::is_convertible_v && + std::is_class_v> && + std::is_convertible_v, std::string_view>; +} // namespace internal +#endif + /** * A builder for JSON strings representing documents. This is a low-level * builder that is not meant to be used directly by end-users. Though it @@ -46195,9 +47392,20 @@ class string_builder { simdjson_inline void append(const T &value); #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + // Contiguous arrays of integers, written without a capacity check per element. + template + requires(!require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; + // Contiguous arrays of strings: one capacity check, then quoted escaped + // elements. Same rationale as the integer-array writer. + template + requires (internal::contiguous_string_range && !require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; // Support for range-based appending (std::ranges::view, etc.) template -requires (!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void append(const R &range) noexcept; #endif /** @@ -46339,6 +47547,14 @@ requires (!std::is_convertible::value && !concepts::optiona simdjson_inline void append_static_string() noexcept; #endif +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + /** + * Append an array of integers too long to reserve its worst case at once. + */ + template + void append_long_integer_array(const int_type *data, size_t n) noexcept; +#endif + /** * Grow the buffer to at least desired_capacity bytes. * If the allocation fails, is_valid is set to false. We expect @@ -46363,6 +47579,18 @@ requires (!std::is_convertible::value && !concepts::optiona bool is_valid{true}; }; +namespace internal { +// Appends value as a JSON value. A char is a one-character string, as in +// append_key_value(): string_builder::append(char) appends a raw character. +template +simdjson_inline void append_value(string_builder &b, const T &value) { + b.append(value); +} +simdjson_inline void append_value(string_builder &b, char value) { + b.escape_and_append_with_quotes(value); +} +} // namespace internal + } @@ -46371,21 +47599,12 @@ requires (!std::is_convertible::value && !concepts::optiona #if !SIMDJSON_STATIC_REFLECTION // fallback implementation until we have static reflection +// Defined in json_string_builder-inl.h so number arrays can write straight +// into the destination string (one allocation, no builder copy). template -simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::arm64::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::arm64::builder::string_builder b(initial_capacity); - b.append(z); - std::string s; - auto e = b.move_to(s); - if(e) { return e; } - return s; -} +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::arm64::builder::string_builder::DEFAULT_INITIAL_CAPACITY); template -simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::arm64::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::arm64::builder::string_builder b(initial_capacity); - b.append(z); - return b.move_to(s); -} +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::arm64::builder::string_builder::DEFAULT_INITIAL_CAPACITY); #endif #if SIMDJSON_SUPPORTS_CONCEPTS @@ -46427,7 +47646,7 @@ namespace builder { // included at the point this header is parsed; without these forwards, // name lookup falls back to the wrong outer namespace). namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; simdjson_inline char *write_double(char *p, double v) noexcept; } // namespace internal @@ -46642,7 +47861,7 @@ template simdjson_really_inline void atom_fields(W &w, const T &t, bool &first) { // Per-field block: ensure key+value worst case, then write key + value // through the writer's local pos. For arithmetic fields, the integer - // write happens directly via write_uint_jeaiii on w.ptr+w.pos, so pos + // write happens directly via write_uint on w.ptr+w.pos, so pos // never round-trips through memory. template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) { if constexpr (is_serialized_member(dm)) { @@ -46791,7 +48010,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { "Integers wider than 64 bits are not supported"); // Booleans / floats: defer to string_builder (rare path; keeps writer hot // path free of float-formatter machinery). For integers, write directly - // via jeaiii using local pos. + // via write_uint using local pos. if constexpr (std::is_same_v) { if (t) { if (!w.ensure(4)) return; @@ -46810,7 +48029,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { } } else if constexpr (std::is_unsigned_v) { if (!w.ensure(20)) return; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(t)); w.pos = static_cast(end - w.ptr); } else { @@ -46821,7 +48040,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { U pv = negative ? U(0) - static_cast(t) : static_cast(t); w.ptr[w.pos] = '-'; w.pos += negative; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(pv)); w.pos = static_cast(end - w.ptr); } @@ -47449,7 +48668,7 @@ simdjson_warn_unused simdjson_result extract_fractured_json( /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #define SIMDJSON_GENERIC_STRING_BUILDER_INL_H */ /* amalgamation skipped (editor-only): #include "simdjson/generic/builder/json_string_builder.h" */ -/* amalgamation skipped (editor-only): #include "simdjson/internal/jeaiii.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/write_uint.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/json_escape.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ @@ -47588,7 +48807,7 @@ simdjson_inline void string_builder::clear() noexcept { namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; // Writes v at p, which must have to_chars_buffer_size bytes available, and // returns the end of what was written. @@ -47605,6 +48824,12 @@ simdjson_inline char *write_double(char *p, double v) noexcept { std::memcpy(p, "Infinity", 8); return p + 8; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(p, "null", 4); + return p + 4; + } #endif return simdjson::internal::to_chars(p, nullptr, v); } @@ -47640,7 +48865,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { constexpr size_t max_number_size = 20; if (capacity_check(max_number_size)) { using unsigned_type = typename std::make_unsigned::type; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(static_cast(v))); position = end - buffer_data(); @@ -47659,7 +48884,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { // Branchless: always write '-', advance only if negative. buffer_data()[position] = '-'; position += negative; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(pv)); position = end - buffer_data(); } @@ -47691,6 +48916,13 @@ simdjson_inline void string_builder::append(number_type v) noexcept { } return; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(buffer_data() + position, "null", 4); + position += 4; + return; + } #endif // We could specialize for float. @@ -47804,7 +49036,7 @@ template requires(!require_custom_serialization) simdjson_inline void string_builder::append(const T &opt) { if (opt) { - append(*opt); + internal::append_value(*this, *opt); } else { append_null(); } @@ -47825,9 +49057,213 @@ simdjson_inline void string_builder::append(const T &value) { #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace internal { +// An element of an integer array takes at most its digits, a sign and a comma. +// write_uint writes past the last digit only below 10^4, and then at most +// four bytes in all, which still fits the bound. +template +constexpr size_t max_integer_element_size = + size_t(std::numeric_limits::digits10) + 2 + + (std::is_signed_v ? 1 : 0); + +// Longer arrays reserve their worst case one block at a time, so that an +// array of short numbers does not reserve many times what it writes. +template +constexpr size_t integer_block_size = + (size_t(1) << 20) / max_integer_element_size; + +template +simdjson_inline char *write_integer(char *p, int_type v) noexcept { + if constexpr (std::is_unsigned_v) { + return write_uint(p, static_cast(v)); + } else { + using unsigned_type = std::make_unsigned_t; + const bool negative = v < 0; + unsigned_type pv = negative ? unsigned_type(0) - static_cast(v) + : static_cast(v); + *p = '-'; + p += negative; + return write_uint(p, static_cast(pv)); + } +} +} // namespace internal + +template + requires(!require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + using int_type = std::ranges::range_value_t; + const int_type *data = std::ranges::data(range); + const size_t n = size_t(std::ranges::size(range)); + if (simdjson_unlikely(n > internal::integer_block_size)) { + append_long_integer_array(data, n); + return; + } + if (!capacity_check(2 + n * internal::max_integer_element_size)) { + return; + } + char *p = buffer_data() + position; + *p++ = '['; + for (size_t i = 0; i < n; i++) { + if (i) { + *p++ = ','; + } + p = internal::write_integer(p, data[i]); + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + +template +simdjson_never_inline void +string_builder::append_long_integer_array(const int_type *data, size_t n) noexcept { + constexpr size_t element_size = internal::max_integer_element_size; + constexpr size_t block_size = internal::integer_block_size; + if (!capacity_check(1)) { + return; + } + const size_t start = position; + buffer_data()[position++] = '['; + size_t i = 0; + while (i < n) { + const size_t count = (n - i < block_size) ? n - i : block_size; + size_t upcoming = count * element_size; + if (i == block_size) { + // Reserve for the remaining elements at the average size seen so far, + // so that the buffer is reallocated about once instead of doubling + // through many sizes. + size_t average = (position - start) / i + 1; + average = average < element_size ? average : element_size; + if (n - i <= (std::numeric_limits::max)() / average) { + const size_t estimate = (n - i) * average; + upcoming = estimate > upcoming ? estimate : upcoming; + } + } + if (!capacity_check(upcoming)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + for (const size_t stop = i + count; i < stop; i++) { + p = internal::write_integer(p, data[i]); + *p++ = ','; + } + position = size_t(p - buffer_data()); + } + // The closing bracket replaces the comma after the last element. + buffer_data()[position - 1] = ']'; +} + +namespace internal { +// Cold path of the string-array writer: the element may not fit its +// worst-case escaped size in the remaining capacity. Writes the element and +// returns the new write pointer, or nullptr if the buffer could not grow. +simdjson_never_inline char *append_quoted_element_slow(string_builder &b, + std::string_view sv, + bool first) noexcept { + auto reserve = [&b](size_t n) { + const size_t pos = b.unsafe_position(); + const size_t cap = b.unsafe_capacity(); + if (n <= cap - pos) { + return true; + } + if (pos + n < pos) { + return false; + } + return b.unsafe_grow((std::max)(cap * 2, pos + n)); + }; + if (sv.size() > 512) { + if (!reserve(6 * sv.size() + 4)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + if (!first) { + *p++ = ','; + } + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + return p; + } + // Escape into a stack buffer first so that we grow by the exact size. + simdjson_indeterminate char tmp[3 + 6 * 512]; + char *tp = tmp; + if (!first) { + *tp++ = ','; + } + *tp++ = '"'; + tp += write_string_escaped(sv, tp); + *tp++ = '"'; + const size_t n = size_t(tp - tmp); + // One more byte for the closing bracket. + if (!reserve(n + 1)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + std::memcpy(p, tmp, n); + return p + n; +} +} // namespace internal + +template + requires (internal::contiguous_string_range && !require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + // Reserve the unescaped size (brackets, commas, quotes, bytes) plus 1/16 + // for escapes. A 6x worst-case reservation made a fresh builder allocate + // several times the output; an exact one made the first escape double + // the buffer. + size_t bytes = 2; + for (const auto &item : range) { + const std::string_view sv = item; + if (sv.size() > ((std::numeric_limits::max)() - 4) / 6 || + sv.size() > (std::numeric_limits::max)() - bytes - 3) { + set_valid(false); + return; + } + bytes += 3 + sv.size(); + } + const size_t slack = bytes / 16; + if (bytes > (std::numeric_limits::max)() - slack) { + set_valid(false); + return; + } + if (!capacity_check(bytes + slack)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + *p++ = '['; + bool first = true; + for (const auto &item : range) { + const std::string_view sv = item; + const size_t off = size_t(p - buffer_data()); + // Comma, two quotes, up to 6 bytes per input byte, closing bracket. + if (simdjson_unlikely(6 * sv.size() + 4 > capacity - off)) { + position = off; + p = internal::append_quoted_element_slow(*this, sv, first); + if (p == nullptr) { + set_valid(false); + return; + } + first = false; + continue; + } + if (!first) { + *p++ = ','; + } + first = false; + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + // Support for range-based appending (std::ranges::view, etc.) template - requires(!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void string_builder::append(const R &range) noexcept { auto it = std::ranges::begin(range); auto end = std::ranges::end(range); @@ -47856,13 +49292,13 @@ simdjson_inline void string_builder::append(const R &range) noexcept { } // Append first item without leading comma - append(*it); + internal::append_value(*this, *it); ++it; // Append remaining items with preceding commas for (; it != end; ++it) { append_comma(); - append(*it); + internal::append_value(*this, *it); } end_array(); } @@ -48062,6 +49498,175 @@ string_builder::append_key_value() noexcept { } // namespace arm64 } // namespace simdjson + +#if !SIMDJSON_STATIC_REFLECTION +namespace simdjson { + +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace builder_to_json_detail { +// Concepts, not constexpr bools: a conjunction of concepts stops at the +// first unsatisfied one, so range_value_t is never formed for a non-range. +template +concept contiguous_number_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !require_custom_serialization; +template +concept contiguous_int_array = + contiguous_number_array && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; +template +concept contiguous_float_array = + contiguous_number_array && + std::is_floating_point_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t); + +// Most bytes one element writes, the comma before it included. A double +// takes at most 24 characters (-d.dddddddddddddddde-308). +template +constexpr size_t max_element_size() { + if constexpr (std::is_floating_point_v) { + return 24 + 1; + } else { + return size_t(std::numeric_limits::digits10) + 1 + std::is_signed_v + 1; + } +} +// The number writers may write scratch bytes past the end of the number. +constexpr size_t write_slack = simdjson::internal::to_chars_buffer_size; +// Arrays whose bound fits are written on the stack, then copied once. +constexpr size_t stack_buffer_size = 1024; + +template +simdjson_inline char *write_element(char *p, T v) noexcept { + if constexpr (std::is_floating_point_v) { + return simdjson::arm64::builder::internal::write_double(p, double(v)); + } else if constexpr (std::is_unsigned_v) { + return simdjson::internal::write_uint(p, static_cast(v)); + } else { + using U = std::make_unsigned_t; + const bool negative = v < 0; + U pv = negative ? U(0) - static_cast(v) : static_cast(v); + *p = '-'; + p += negative; + return simdjson::internal::write_uint(p, static_cast(pv)); + } +} + +template +simdjson_inline char *write_array(char *p, const T *data, size_t n) noexcept { + *p++ = '['; + if (n) { + p = write_element(p, data[0]); + for (size_t i = 1; i < n; i++) { + *p++ = ','; + p = write_element(p, data[i]); + } + } + *p++ = ']'; + return p; +} + +// Not simdjson_inline: MSVC cannot force-inline a function with a try block (C4714). +inline bool assign_bytes(std::string &s, const char *data, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + s.assign(data, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + // Without exceptions, a failed allocation terminates the program. + s.assign(data, n); +#endif + return true; +} + +inline bool resize_for_direct_write(std::string &s, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + simdjson::arm64::builder::internal::resize_uninitialized(s, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + simdjson::arm64::builder::internal::resize_uninitialized(s, n); +#endif + return true; +} + +// A result that fills at most half of the allocation is copied out, as in +// string_builder::move_to. On failure s keeps the larger buffer. +simdjson_never_inline void shrink_to_size(std::string &s) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + std::string(s).swap(s); + } catch (...) { // std::bad_alloc + } +#else + std::string(s).swap(s); +#endif +} + +template +simdjson_warn_unused error_code to_json_array(const T *data, size_t n, std::string &s) noexcept { + constexpr size_t per = max_element_size(); + if (simdjson_unlikely(n > (size_t(-1) - 2 - write_slack) / per)) { + return MEMALLOC; + } + const size_t bound = n * per + 2 + write_slack; + if (bound <= stack_buffer_size) { + simdjson_indeterminate char buffer[stack_buffer_size]; + char *end = write_array(buffer, data, n); + return assign_bytes(s, buffer, size_t(end - buffer)) ? SUCCESS : MEMALLOC; + } + const size_t old_capacity = s.capacity(); + if (!resize_for_direct_write(s, bound)) { + return MEMALLOC; + } + char *begin = &s[0]; + const size_t used = size_t(write_array(begin, data, n) - begin); + s.resize(used); + // A string that could already hold the result is being reused: keep its + // buffer so the next call does not allocate again. + if (old_capacity < used && used <= s.capacity() / 2) { + shrink_to_size(s); + } + return SUCCESS; +} +} // namespace builder_to_json_detail +#endif // SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + +template +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity) { +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + if constexpr (builder_to_json_detail::contiguous_int_array || + builder_to_json_detail::contiguous_float_array) { + (void)initial_capacity; + return builder_to_json_detail::to_json_array(std::ranges::data(z), size_t(std::ranges::size(z)), s); + } else +#endif + { + simdjson::arm64::builder::string_builder b(initial_capacity); + simdjson::arm64::builder::internal::append_value(b, z); + return b.move_to(s); + } +} + +template +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity) { + std::string s; + auto e = to_json(z, s, initial_capacity); + if (e) { return e; } + return s; +} + +} // namespace simdjson +#endif // !SIMDJSON_STATIC_REFLECTION + #endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H /* end file simdjson/generic/builder/json_string_builder-inl.h for arm64 */ @@ -48223,6 +49828,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/fallback/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -48238,14 +49844,11 @@ namespace simdjson { namespace fallback { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; - memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + std::memcpy(&val, chars, sizeof(uint64_t)); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -48358,6 +49961,36 @@ namespace builder { using simdjson::internal::escape_best::write_string_escaped; +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +/** + * A contiguous, sized range of integers that string_builder serializes as a + * JSON array of numbers in one pass. Booleans and character types are excluded, + * and so are integers wider than 64 bits. In C++26, std::optional is a + * contiguous range: it is excluded so that the optional overload is chosen. + */ +template +concept integer_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !concepts::optional_type && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; + +namespace internal { +// Elements must be class types (std::string, std::string_view, ...): a +// range of const char * would pay strlen twice. +template +concept contiguous_string_range = + std::ranges::contiguous_range && !concepts::optional_type && + !std::is_convertible_v && + std::is_class_v> && + std::is_convertible_v, std::string_view>; +} // namespace internal +#endif + /** * A builder for JSON strings representing documents. This is a low-level * builder that is not meant to be used directly by end-users. Though it @@ -48511,9 +50144,20 @@ class string_builder { simdjson_inline void append(const T &value); #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + // Contiguous arrays of integers, written without a capacity check per element. + template + requires(!require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; + // Contiguous arrays of strings: one capacity check, then quoted escaped + // elements. Same rationale as the integer-array writer. + template + requires (internal::contiguous_string_range && !require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; // Support for range-based appending (std::ranges::view, etc.) template -requires (!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void append(const R &range) noexcept; #endif /** @@ -48655,6 +50299,14 @@ requires (!std::is_convertible::value && !concepts::optiona simdjson_inline void append_static_string() noexcept; #endif +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + /** + * Append an array of integers too long to reserve its worst case at once. + */ + template + void append_long_integer_array(const int_type *data, size_t n) noexcept; +#endif + /** * Grow the buffer to at least desired_capacity bytes. * If the allocation fails, is_valid is set to false. We expect @@ -48679,6 +50331,18 @@ requires (!std::is_convertible::value && !concepts::optiona bool is_valid{true}; }; +namespace internal { +// Appends value as a JSON value. A char is a one-character string, as in +// append_key_value(): string_builder::append(char) appends a raw character. +template +simdjson_inline void append_value(string_builder &b, const T &value) { + b.append(value); +} +simdjson_inline void append_value(string_builder &b, char value) { + b.escape_and_append_with_quotes(value); +} +} // namespace internal + } @@ -48687,21 +50351,12 @@ requires (!std::is_convertible::value && !concepts::optiona #if !SIMDJSON_STATIC_REFLECTION // fallback implementation until we have static reflection +// Defined in json_string_builder-inl.h so number arrays can write straight +// into the destination string (one allocation, no builder copy). template -simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::fallback::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::fallback::builder::string_builder b(initial_capacity); - b.append(z); - std::string s; - auto e = b.move_to(s); - if(e) { return e; } - return s; -} +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::fallback::builder::string_builder::DEFAULT_INITIAL_CAPACITY); template -simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::fallback::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::fallback::builder::string_builder b(initial_capacity); - b.append(z); - return b.move_to(s); -} +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::fallback::builder::string_builder::DEFAULT_INITIAL_CAPACITY); #endif #if SIMDJSON_SUPPORTS_CONCEPTS @@ -48743,7 +50398,7 @@ namespace builder { // included at the point this header is parsed; without these forwards, // name lookup falls back to the wrong outer namespace). namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; simdjson_inline char *write_double(char *p, double v) noexcept; } // namespace internal @@ -48958,7 +50613,7 @@ template simdjson_really_inline void atom_fields(W &w, const T &t, bool &first) { // Per-field block: ensure key+value worst case, then write key + value // through the writer's local pos. For arithmetic fields, the integer - // write happens directly via write_uint_jeaiii on w.ptr+w.pos, so pos + // write happens directly via write_uint on w.ptr+w.pos, so pos // never round-trips through memory. template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) { if constexpr (is_serialized_member(dm)) { @@ -49107,7 +50762,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { "Integers wider than 64 bits are not supported"); // Booleans / floats: defer to string_builder (rare path; keeps writer hot // path free of float-formatter machinery). For integers, write directly - // via jeaiii using local pos. + // via write_uint using local pos. if constexpr (std::is_same_v) { if (t) { if (!w.ensure(4)) return; @@ -49126,7 +50781,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { } } else if constexpr (std::is_unsigned_v) { if (!w.ensure(20)) return; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(t)); w.pos = static_cast(end - w.ptr); } else { @@ -49137,7 +50792,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { U pv = negative ? U(0) - static_cast(t) : static_cast(t); w.ptr[w.pos] = '-'; w.pos += negative; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(pv)); w.pos = static_cast(end - w.ptr); } @@ -49765,7 +51420,7 @@ simdjson_warn_unused simdjson_result extract_fractured_json( /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #define SIMDJSON_GENERIC_STRING_BUILDER_INL_H */ /* amalgamation skipped (editor-only): #include "simdjson/generic/builder/json_string_builder.h" */ -/* amalgamation skipped (editor-only): #include "simdjson/internal/jeaiii.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/write_uint.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/json_escape.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ @@ -49904,7 +51559,7 @@ simdjson_inline void string_builder::clear() noexcept { namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; // Writes v at p, which must have to_chars_buffer_size bytes available, and // returns the end of what was written. @@ -49921,6 +51576,12 @@ simdjson_inline char *write_double(char *p, double v) noexcept { std::memcpy(p, "Infinity", 8); return p + 8; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(p, "null", 4); + return p + 4; + } #endif return simdjson::internal::to_chars(p, nullptr, v); } @@ -49956,7 +51617,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { constexpr size_t max_number_size = 20; if (capacity_check(max_number_size)) { using unsigned_type = typename std::make_unsigned::type; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(static_cast(v))); position = end - buffer_data(); @@ -49975,7 +51636,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { // Branchless: always write '-', advance only if negative. buffer_data()[position] = '-'; position += negative; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(pv)); position = end - buffer_data(); } @@ -50007,6 +51668,13 @@ simdjson_inline void string_builder::append(number_type v) noexcept { } return; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(buffer_data() + position, "null", 4); + position += 4; + return; + } #endif // We could specialize for float. @@ -50120,7 +51788,7 @@ template requires(!require_custom_serialization) simdjson_inline void string_builder::append(const T &opt) { if (opt) { - append(*opt); + internal::append_value(*this, *opt); } else { append_null(); } @@ -50141,9 +51809,213 @@ simdjson_inline void string_builder::append(const T &value) { #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace internal { +// An element of an integer array takes at most its digits, a sign and a comma. +// write_uint writes past the last digit only below 10^4, and then at most +// four bytes in all, which still fits the bound. +template +constexpr size_t max_integer_element_size = + size_t(std::numeric_limits::digits10) + 2 + + (std::is_signed_v ? 1 : 0); + +// Longer arrays reserve their worst case one block at a time, so that an +// array of short numbers does not reserve many times what it writes. +template +constexpr size_t integer_block_size = + (size_t(1) << 20) / max_integer_element_size; + +template +simdjson_inline char *write_integer(char *p, int_type v) noexcept { + if constexpr (std::is_unsigned_v) { + return write_uint(p, static_cast(v)); + } else { + using unsigned_type = std::make_unsigned_t; + const bool negative = v < 0; + unsigned_type pv = negative ? unsigned_type(0) - static_cast(v) + : static_cast(v); + *p = '-'; + p += negative; + return write_uint(p, static_cast(pv)); + } +} +} // namespace internal + +template + requires(!require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + using int_type = std::ranges::range_value_t; + const int_type *data = std::ranges::data(range); + const size_t n = size_t(std::ranges::size(range)); + if (simdjson_unlikely(n > internal::integer_block_size)) { + append_long_integer_array(data, n); + return; + } + if (!capacity_check(2 + n * internal::max_integer_element_size)) { + return; + } + char *p = buffer_data() + position; + *p++ = '['; + for (size_t i = 0; i < n; i++) { + if (i) { + *p++ = ','; + } + p = internal::write_integer(p, data[i]); + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + +template +simdjson_never_inline void +string_builder::append_long_integer_array(const int_type *data, size_t n) noexcept { + constexpr size_t element_size = internal::max_integer_element_size; + constexpr size_t block_size = internal::integer_block_size; + if (!capacity_check(1)) { + return; + } + const size_t start = position; + buffer_data()[position++] = '['; + size_t i = 0; + while (i < n) { + const size_t count = (n - i < block_size) ? n - i : block_size; + size_t upcoming = count * element_size; + if (i == block_size) { + // Reserve for the remaining elements at the average size seen so far, + // so that the buffer is reallocated about once instead of doubling + // through many sizes. + size_t average = (position - start) / i + 1; + average = average < element_size ? average : element_size; + if (n - i <= (std::numeric_limits::max)() / average) { + const size_t estimate = (n - i) * average; + upcoming = estimate > upcoming ? estimate : upcoming; + } + } + if (!capacity_check(upcoming)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + for (const size_t stop = i + count; i < stop; i++) { + p = internal::write_integer(p, data[i]); + *p++ = ','; + } + position = size_t(p - buffer_data()); + } + // The closing bracket replaces the comma after the last element. + buffer_data()[position - 1] = ']'; +} + +namespace internal { +// Cold path of the string-array writer: the element may not fit its +// worst-case escaped size in the remaining capacity. Writes the element and +// returns the new write pointer, or nullptr if the buffer could not grow. +simdjson_never_inline char *append_quoted_element_slow(string_builder &b, + std::string_view sv, + bool first) noexcept { + auto reserve = [&b](size_t n) { + const size_t pos = b.unsafe_position(); + const size_t cap = b.unsafe_capacity(); + if (n <= cap - pos) { + return true; + } + if (pos + n < pos) { + return false; + } + return b.unsafe_grow((std::max)(cap * 2, pos + n)); + }; + if (sv.size() > 512) { + if (!reserve(6 * sv.size() + 4)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + if (!first) { + *p++ = ','; + } + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + return p; + } + // Escape into a stack buffer first so that we grow by the exact size. + simdjson_indeterminate char tmp[3 + 6 * 512]; + char *tp = tmp; + if (!first) { + *tp++ = ','; + } + *tp++ = '"'; + tp += write_string_escaped(sv, tp); + *tp++ = '"'; + const size_t n = size_t(tp - tmp); + // One more byte for the closing bracket. + if (!reserve(n + 1)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + std::memcpy(p, tmp, n); + return p + n; +} +} // namespace internal + +template + requires (internal::contiguous_string_range && !require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + // Reserve the unescaped size (brackets, commas, quotes, bytes) plus 1/16 + // for escapes. A 6x worst-case reservation made a fresh builder allocate + // several times the output; an exact one made the first escape double + // the buffer. + size_t bytes = 2; + for (const auto &item : range) { + const std::string_view sv = item; + if (sv.size() > ((std::numeric_limits::max)() - 4) / 6 || + sv.size() > (std::numeric_limits::max)() - bytes - 3) { + set_valid(false); + return; + } + bytes += 3 + sv.size(); + } + const size_t slack = bytes / 16; + if (bytes > (std::numeric_limits::max)() - slack) { + set_valid(false); + return; + } + if (!capacity_check(bytes + slack)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + *p++ = '['; + bool first = true; + for (const auto &item : range) { + const std::string_view sv = item; + const size_t off = size_t(p - buffer_data()); + // Comma, two quotes, up to 6 bytes per input byte, closing bracket. + if (simdjson_unlikely(6 * sv.size() + 4 > capacity - off)) { + position = off; + p = internal::append_quoted_element_slow(*this, sv, first); + if (p == nullptr) { + set_valid(false); + return; + } + first = false; + continue; + } + if (!first) { + *p++ = ','; + } + first = false; + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + // Support for range-based appending (std::ranges::view, etc.) template - requires(!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void string_builder::append(const R &range) noexcept { auto it = std::ranges::begin(range); auto end = std::ranges::end(range); @@ -50172,13 +52044,13 @@ simdjson_inline void string_builder::append(const R &range) noexcept { } // Append first item without leading comma - append(*it); + internal::append_value(*this, *it); ++it; // Append remaining items with preceding commas for (; it != end; ++it) { append_comma(); - append(*it); + internal::append_value(*this, *it); } end_array(); } @@ -50378,6 +52250,175 @@ string_builder::append_key_value() noexcept { } // namespace fallback } // namespace simdjson + +#if !SIMDJSON_STATIC_REFLECTION +namespace simdjson { + +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace builder_to_json_detail { +// Concepts, not constexpr bools: a conjunction of concepts stops at the +// first unsatisfied one, so range_value_t is never formed for a non-range. +template +concept contiguous_number_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !require_custom_serialization; +template +concept contiguous_int_array = + contiguous_number_array && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; +template +concept contiguous_float_array = + contiguous_number_array && + std::is_floating_point_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t); + +// Most bytes one element writes, the comma before it included. A double +// takes at most 24 characters (-d.dddddddddddddddde-308). +template +constexpr size_t max_element_size() { + if constexpr (std::is_floating_point_v) { + return 24 + 1; + } else { + return size_t(std::numeric_limits::digits10) + 1 + std::is_signed_v + 1; + } +} +// The number writers may write scratch bytes past the end of the number. +constexpr size_t write_slack = simdjson::internal::to_chars_buffer_size; +// Arrays whose bound fits are written on the stack, then copied once. +constexpr size_t stack_buffer_size = 1024; + +template +simdjson_inline char *write_element(char *p, T v) noexcept { + if constexpr (std::is_floating_point_v) { + return simdjson::fallback::builder::internal::write_double(p, double(v)); + } else if constexpr (std::is_unsigned_v) { + return simdjson::internal::write_uint(p, static_cast(v)); + } else { + using U = std::make_unsigned_t; + const bool negative = v < 0; + U pv = negative ? U(0) - static_cast(v) : static_cast(v); + *p = '-'; + p += negative; + return simdjson::internal::write_uint(p, static_cast(pv)); + } +} + +template +simdjson_inline char *write_array(char *p, const T *data, size_t n) noexcept { + *p++ = '['; + if (n) { + p = write_element(p, data[0]); + for (size_t i = 1; i < n; i++) { + *p++ = ','; + p = write_element(p, data[i]); + } + } + *p++ = ']'; + return p; +} + +// Not simdjson_inline: MSVC cannot force-inline a function with a try block (C4714). +inline bool assign_bytes(std::string &s, const char *data, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + s.assign(data, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + // Without exceptions, a failed allocation terminates the program. + s.assign(data, n); +#endif + return true; +} + +inline bool resize_for_direct_write(std::string &s, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + simdjson::fallback::builder::internal::resize_uninitialized(s, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + simdjson::fallback::builder::internal::resize_uninitialized(s, n); +#endif + return true; +} + +// A result that fills at most half of the allocation is copied out, as in +// string_builder::move_to. On failure s keeps the larger buffer. +simdjson_never_inline void shrink_to_size(std::string &s) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + std::string(s).swap(s); + } catch (...) { // std::bad_alloc + } +#else + std::string(s).swap(s); +#endif +} + +template +simdjson_warn_unused error_code to_json_array(const T *data, size_t n, std::string &s) noexcept { + constexpr size_t per = max_element_size(); + if (simdjson_unlikely(n > (size_t(-1) - 2 - write_slack) / per)) { + return MEMALLOC; + } + const size_t bound = n * per + 2 + write_slack; + if (bound <= stack_buffer_size) { + simdjson_indeterminate char buffer[stack_buffer_size]; + char *end = write_array(buffer, data, n); + return assign_bytes(s, buffer, size_t(end - buffer)) ? SUCCESS : MEMALLOC; + } + const size_t old_capacity = s.capacity(); + if (!resize_for_direct_write(s, bound)) { + return MEMALLOC; + } + char *begin = &s[0]; + const size_t used = size_t(write_array(begin, data, n) - begin); + s.resize(used); + // A string that could already hold the result is being reused: keep its + // buffer so the next call does not allocate again. + if (old_capacity < used && used <= s.capacity() / 2) { + shrink_to_size(s); + } + return SUCCESS; +} +} // namespace builder_to_json_detail +#endif // SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + +template +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity) { +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + if constexpr (builder_to_json_detail::contiguous_int_array || + builder_to_json_detail::contiguous_float_array) { + (void)initial_capacity; + return builder_to_json_detail::to_json_array(std::ranges::data(z), size_t(std::ranges::size(z)), s); + } else +#endif + { + simdjson::fallback::builder::string_builder b(initial_capacity); + simdjson::fallback::builder::internal::append_value(b, z); + return b.move_to(s); + } +} + +template +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity) { + std::string s; + auto e = to_json(z, s, initial_capacity); + if (e) { return e; } + return s; +} + +} // namespace simdjson +#endif // !SIMDJSON_STATIC_REFLECTION + #endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H /* end file simdjson/generic/builder/json_string_builder-inl.h for fallback */ @@ -50672,6 +52713,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/haswell/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/haswell/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -50894,6 +52936,26 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + const __m128i lo = n >= 16 ? _mm_loadu_si128(reinterpret_cast(ptr)) : load_partial_16(ptr, n, begin, fill); + const __m128i hi = n > 16 ? load_partial_16(ptr + 16, n - 16, begin, fill) : _mm_set1_epi8(char(fill)); + return _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -51144,6 +53206,36 @@ namespace builder { using simdjson::internal::escape_best::write_string_escaped; +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +/** + * A contiguous, sized range of integers that string_builder serializes as a + * JSON array of numbers in one pass. Booleans and character types are excluded, + * and so are integers wider than 64 bits. In C++26, std::optional is a + * contiguous range: it is excluded so that the optional overload is chosen. + */ +template +concept integer_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !concepts::optional_type && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; + +namespace internal { +// Elements must be class types (std::string, std::string_view, ...): a +// range of const char * would pay strlen twice. +template +concept contiguous_string_range = + std::ranges::contiguous_range && !concepts::optional_type && + !std::is_convertible_v && + std::is_class_v> && + std::is_convertible_v, std::string_view>; +} // namespace internal +#endif + /** * A builder for JSON strings representing documents. This is a low-level * builder that is not meant to be used directly by end-users. Though it @@ -51297,9 +53389,20 @@ class string_builder { simdjson_inline void append(const T &value); #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + // Contiguous arrays of integers, written without a capacity check per element. + template + requires(!require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; + // Contiguous arrays of strings: one capacity check, then quoted escaped + // elements. Same rationale as the integer-array writer. + template + requires (internal::contiguous_string_range && !require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; // Support for range-based appending (std::ranges::view, etc.) template -requires (!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void append(const R &range) noexcept; #endif /** @@ -51441,6 +53544,14 @@ requires (!std::is_convertible::value && !concepts::optiona simdjson_inline void append_static_string() noexcept; #endif +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + /** + * Append an array of integers too long to reserve its worst case at once. + */ + template + void append_long_integer_array(const int_type *data, size_t n) noexcept; +#endif + /** * Grow the buffer to at least desired_capacity bytes. * If the allocation fails, is_valid is set to false. We expect @@ -51465,6 +53576,18 @@ requires (!std::is_convertible::value && !concepts::optiona bool is_valid{true}; }; +namespace internal { +// Appends value as a JSON value. A char is a one-character string, as in +// append_key_value(): string_builder::append(char) appends a raw character. +template +simdjson_inline void append_value(string_builder &b, const T &value) { + b.append(value); +} +simdjson_inline void append_value(string_builder &b, char value) { + b.escape_and_append_with_quotes(value); +} +} // namespace internal + } @@ -51473,21 +53596,12 @@ requires (!std::is_convertible::value && !concepts::optiona #if !SIMDJSON_STATIC_REFLECTION // fallback implementation until we have static reflection +// Defined in json_string_builder-inl.h so number arrays can write straight +// into the destination string (one allocation, no builder copy). template -simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::haswell::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::haswell::builder::string_builder b(initial_capacity); - b.append(z); - std::string s; - auto e = b.move_to(s); - if(e) { return e; } - return s; -} +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::haswell::builder::string_builder::DEFAULT_INITIAL_CAPACITY); template -simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::haswell::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::haswell::builder::string_builder b(initial_capacity); - b.append(z); - return b.move_to(s); -} +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::haswell::builder::string_builder::DEFAULT_INITIAL_CAPACITY); #endif #if SIMDJSON_SUPPORTS_CONCEPTS @@ -51529,7 +53643,7 @@ namespace builder { // included at the point this header is parsed; without these forwards, // name lookup falls back to the wrong outer namespace). namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; simdjson_inline char *write_double(char *p, double v) noexcept; } // namespace internal @@ -51744,7 +53858,7 @@ template simdjson_really_inline void atom_fields(W &w, const T &t, bool &first) { // Per-field block: ensure key+value worst case, then write key + value // through the writer's local pos. For arithmetic fields, the integer - // write happens directly via write_uint_jeaiii on w.ptr+w.pos, so pos + // write happens directly via write_uint on w.ptr+w.pos, so pos // never round-trips through memory. template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) { if constexpr (is_serialized_member(dm)) { @@ -51893,7 +54007,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { "Integers wider than 64 bits are not supported"); // Booleans / floats: defer to string_builder (rare path; keeps writer hot // path free of float-formatter machinery). For integers, write directly - // via jeaiii using local pos. + // via write_uint using local pos. if constexpr (std::is_same_v) { if (t) { if (!w.ensure(4)) return; @@ -51912,7 +54026,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { } } else if constexpr (std::is_unsigned_v) { if (!w.ensure(20)) return; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(t)); w.pos = static_cast(end - w.ptr); } else { @@ -51923,7 +54037,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { U pv = negative ? U(0) - static_cast(t) : static_cast(t); w.ptr[w.pos] = '-'; w.pos += negative; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(pv)); w.pos = static_cast(end - w.ptr); } @@ -52551,7 +54665,7 @@ simdjson_warn_unused simdjson_result extract_fractured_json( /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #define SIMDJSON_GENERIC_STRING_BUILDER_INL_H */ /* amalgamation skipped (editor-only): #include "simdjson/generic/builder/json_string_builder.h" */ -/* amalgamation skipped (editor-only): #include "simdjson/internal/jeaiii.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/write_uint.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/json_escape.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ @@ -52690,7 +54804,7 @@ simdjson_inline void string_builder::clear() noexcept { namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; // Writes v at p, which must have to_chars_buffer_size bytes available, and // returns the end of what was written. @@ -52707,6 +54821,12 @@ simdjson_inline char *write_double(char *p, double v) noexcept { std::memcpy(p, "Infinity", 8); return p + 8; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(p, "null", 4); + return p + 4; + } #endif return simdjson::internal::to_chars(p, nullptr, v); } @@ -52742,7 +54862,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { constexpr size_t max_number_size = 20; if (capacity_check(max_number_size)) { using unsigned_type = typename std::make_unsigned::type; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(static_cast(v))); position = end - buffer_data(); @@ -52761,7 +54881,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { // Branchless: always write '-', advance only if negative. buffer_data()[position] = '-'; position += negative; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(pv)); position = end - buffer_data(); } @@ -52793,6 +54913,13 @@ simdjson_inline void string_builder::append(number_type v) noexcept { } return; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(buffer_data() + position, "null", 4); + position += 4; + return; + } #endif // We could specialize for float. @@ -52906,7 +55033,7 @@ template requires(!require_custom_serialization) simdjson_inline void string_builder::append(const T &opt) { if (opt) { - append(*opt); + internal::append_value(*this, *opt); } else { append_null(); } @@ -52927,9 +55054,213 @@ simdjson_inline void string_builder::append(const T &value) { #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace internal { +// An element of an integer array takes at most its digits, a sign and a comma. +// write_uint writes past the last digit only below 10^4, and then at most +// four bytes in all, which still fits the bound. +template +constexpr size_t max_integer_element_size = + size_t(std::numeric_limits::digits10) + 2 + + (std::is_signed_v ? 1 : 0); + +// Longer arrays reserve their worst case one block at a time, so that an +// array of short numbers does not reserve many times what it writes. +template +constexpr size_t integer_block_size = + (size_t(1) << 20) / max_integer_element_size; + +template +simdjson_inline char *write_integer(char *p, int_type v) noexcept { + if constexpr (std::is_unsigned_v) { + return write_uint(p, static_cast(v)); + } else { + using unsigned_type = std::make_unsigned_t; + const bool negative = v < 0; + unsigned_type pv = negative ? unsigned_type(0) - static_cast(v) + : static_cast(v); + *p = '-'; + p += negative; + return write_uint(p, static_cast(pv)); + } +} +} // namespace internal + +template + requires(!require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + using int_type = std::ranges::range_value_t; + const int_type *data = std::ranges::data(range); + const size_t n = size_t(std::ranges::size(range)); + if (simdjson_unlikely(n > internal::integer_block_size)) { + append_long_integer_array(data, n); + return; + } + if (!capacity_check(2 + n * internal::max_integer_element_size)) { + return; + } + char *p = buffer_data() + position; + *p++ = '['; + for (size_t i = 0; i < n; i++) { + if (i) { + *p++ = ','; + } + p = internal::write_integer(p, data[i]); + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + +template +simdjson_never_inline void +string_builder::append_long_integer_array(const int_type *data, size_t n) noexcept { + constexpr size_t element_size = internal::max_integer_element_size; + constexpr size_t block_size = internal::integer_block_size; + if (!capacity_check(1)) { + return; + } + const size_t start = position; + buffer_data()[position++] = '['; + size_t i = 0; + while (i < n) { + const size_t count = (n - i < block_size) ? n - i : block_size; + size_t upcoming = count * element_size; + if (i == block_size) { + // Reserve for the remaining elements at the average size seen so far, + // so that the buffer is reallocated about once instead of doubling + // through many sizes. + size_t average = (position - start) / i + 1; + average = average < element_size ? average : element_size; + if (n - i <= (std::numeric_limits::max)() / average) { + const size_t estimate = (n - i) * average; + upcoming = estimate > upcoming ? estimate : upcoming; + } + } + if (!capacity_check(upcoming)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + for (const size_t stop = i + count; i < stop; i++) { + p = internal::write_integer(p, data[i]); + *p++ = ','; + } + position = size_t(p - buffer_data()); + } + // The closing bracket replaces the comma after the last element. + buffer_data()[position - 1] = ']'; +} + +namespace internal { +// Cold path of the string-array writer: the element may not fit its +// worst-case escaped size in the remaining capacity. Writes the element and +// returns the new write pointer, or nullptr if the buffer could not grow. +simdjson_never_inline char *append_quoted_element_slow(string_builder &b, + std::string_view sv, + bool first) noexcept { + auto reserve = [&b](size_t n) { + const size_t pos = b.unsafe_position(); + const size_t cap = b.unsafe_capacity(); + if (n <= cap - pos) { + return true; + } + if (pos + n < pos) { + return false; + } + return b.unsafe_grow((std::max)(cap * 2, pos + n)); + }; + if (sv.size() > 512) { + if (!reserve(6 * sv.size() + 4)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + if (!first) { + *p++ = ','; + } + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + return p; + } + // Escape into a stack buffer first so that we grow by the exact size. + simdjson_indeterminate char tmp[3 + 6 * 512]; + char *tp = tmp; + if (!first) { + *tp++ = ','; + } + *tp++ = '"'; + tp += write_string_escaped(sv, tp); + *tp++ = '"'; + const size_t n = size_t(tp - tmp); + // One more byte for the closing bracket. + if (!reserve(n + 1)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + std::memcpy(p, tmp, n); + return p + n; +} +} // namespace internal + +template + requires (internal::contiguous_string_range && !require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + // Reserve the unescaped size (brackets, commas, quotes, bytes) plus 1/16 + // for escapes. A 6x worst-case reservation made a fresh builder allocate + // several times the output; an exact one made the first escape double + // the buffer. + size_t bytes = 2; + for (const auto &item : range) { + const std::string_view sv = item; + if (sv.size() > ((std::numeric_limits::max)() - 4) / 6 || + sv.size() > (std::numeric_limits::max)() - bytes - 3) { + set_valid(false); + return; + } + bytes += 3 + sv.size(); + } + const size_t slack = bytes / 16; + if (bytes > (std::numeric_limits::max)() - slack) { + set_valid(false); + return; + } + if (!capacity_check(bytes + slack)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + *p++ = '['; + bool first = true; + for (const auto &item : range) { + const std::string_view sv = item; + const size_t off = size_t(p - buffer_data()); + // Comma, two quotes, up to 6 bytes per input byte, closing bracket. + if (simdjson_unlikely(6 * sv.size() + 4 > capacity - off)) { + position = off; + p = internal::append_quoted_element_slow(*this, sv, first); + if (p == nullptr) { + set_valid(false); + return; + } + first = false; + continue; + } + if (!first) { + *p++ = ','; + } + first = false; + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + // Support for range-based appending (std::ranges::view, etc.) template - requires(!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void string_builder::append(const R &range) noexcept { auto it = std::ranges::begin(range); auto end = std::ranges::end(range); @@ -52958,13 +55289,13 @@ simdjson_inline void string_builder::append(const R &range) noexcept { } // Append first item without leading comma - append(*it); + internal::append_value(*this, *it); ++it; // Append remaining items with preceding commas for (; it != end; ++it) { append_comma(); - append(*it); + internal::append_value(*this, *it); } end_array(); } @@ -53164,6 +55495,175 @@ string_builder::append_key_value() noexcept { } // namespace haswell } // namespace simdjson + +#if !SIMDJSON_STATIC_REFLECTION +namespace simdjson { + +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace builder_to_json_detail { +// Concepts, not constexpr bools: a conjunction of concepts stops at the +// first unsatisfied one, so range_value_t is never formed for a non-range. +template +concept contiguous_number_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !require_custom_serialization; +template +concept contiguous_int_array = + contiguous_number_array && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; +template +concept contiguous_float_array = + contiguous_number_array && + std::is_floating_point_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t); + +// Most bytes one element writes, the comma before it included. A double +// takes at most 24 characters (-d.dddddddddddddddde-308). +template +constexpr size_t max_element_size() { + if constexpr (std::is_floating_point_v) { + return 24 + 1; + } else { + return size_t(std::numeric_limits::digits10) + 1 + std::is_signed_v + 1; + } +} +// The number writers may write scratch bytes past the end of the number. +constexpr size_t write_slack = simdjson::internal::to_chars_buffer_size; +// Arrays whose bound fits are written on the stack, then copied once. +constexpr size_t stack_buffer_size = 1024; + +template +simdjson_inline char *write_element(char *p, T v) noexcept { + if constexpr (std::is_floating_point_v) { + return simdjson::haswell::builder::internal::write_double(p, double(v)); + } else if constexpr (std::is_unsigned_v) { + return simdjson::internal::write_uint(p, static_cast(v)); + } else { + using U = std::make_unsigned_t; + const bool negative = v < 0; + U pv = negative ? U(0) - static_cast(v) : static_cast(v); + *p = '-'; + p += negative; + return simdjson::internal::write_uint(p, static_cast(pv)); + } +} + +template +simdjson_inline char *write_array(char *p, const T *data, size_t n) noexcept { + *p++ = '['; + if (n) { + p = write_element(p, data[0]); + for (size_t i = 1; i < n; i++) { + *p++ = ','; + p = write_element(p, data[i]); + } + } + *p++ = ']'; + return p; +} + +// Not simdjson_inline: MSVC cannot force-inline a function with a try block (C4714). +inline bool assign_bytes(std::string &s, const char *data, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + s.assign(data, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + // Without exceptions, a failed allocation terminates the program. + s.assign(data, n); +#endif + return true; +} + +inline bool resize_for_direct_write(std::string &s, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + simdjson::haswell::builder::internal::resize_uninitialized(s, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + simdjson::haswell::builder::internal::resize_uninitialized(s, n); +#endif + return true; +} + +// A result that fills at most half of the allocation is copied out, as in +// string_builder::move_to. On failure s keeps the larger buffer. +simdjson_never_inline void shrink_to_size(std::string &s) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + std::string(s).swap(s); + } catch (...) { // std::bad_alloc + } +#else + std::string(s).swap(s); +#endif +} + +template +simdjson_warn_unused error_code to_json_array(const T *data, size_t n, std::string &s) noexcept { + constexpr size_t per = max_element_size(); + if (simdjson_unlikely(n > (size_t(-1) - 2 - write_slack) / per)) { + return MEMALLOC; + } + const size_t bound = n * per + 2 + write_slack; + if (bound <= stack_buffer_size) { + simdjson_indeterminate char buffer[stack_buffer_size]; + char *end = write_array(buffer, data, n); + return assign_bytes(s, buffer, size_t(end - buffer)) ? SUCCESS : MEMALLOC; + } + const size_t old_capacity = s.capacity(); + if (!resize_for_direct_write(s, bound)) { + return MEMALLOC; + } + char *begin = &s[0]; + const size_t used = size_t(write_array(begin, data, n) - begin); + s.resize(used); + // A string that could already hold the result is being reused: keep its + // buffer so the next call does not allocate again. + if (old_capacity < used && used <= s.capacity() / 2) { + shrink_to_size(s); + } + return SUCCESS; +} +} // namespace builder_to_json_detail +#endif // SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + +template +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity) { +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + if constexpr (builder_to_json_detail::contiguous_int_array || + builder_to_json_detail::contiguous_float_array) { + (void)initial_capacity; + return builder_to_json_detail::to_json_array(std::ranges::data(z), size_t(std::ranges::size(z)), s); + } else +#endif + { + simdjson::haswell::builder::string_builder b(initial_capacity); + simdjson::haswell::builder::internal::append_value(b, z); + return b.move_to(s); + } +} + +template +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity) { + std::string s; + auto e = to_json(z, s, initial_capacity); + if (e) { return e; } + return s; +} + +} // namespace simdjson +#endif // !SIMDJSON_STATIC_REFLECTION + #endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H /* end file simdjson/generic/builder/json_string_builder-inl.h for haswell */ @@ -53619,6 +56119,12 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 64 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + // Masked-off bytes are not read, so they cannot fault. + return _mm512_mask_loadu_epi8(_mm512_set1_epi8(char(fill)), (uint64_t(1) << n) - 1, ptr); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m512i _value) : base8_numeric(_value) {} // Splat constructor @@ -53926,6 +56432,36 @@ namespace builder { using simdjson::internal::escape_best::write_string_escaped; +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +/** + * A contiguous, sized range of integers that string_builder serializes as a + * JSON array of numbers in one pass. Booleans and character types are excluded, + * and so are integers wider than 64 bits. In C++26, std::optional is a + * contiguous range: it is excluded so that the optional overload is chosen. + */ +template +concept integer_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !concepts::optional_type && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; + +namespace internal { +// Elements must be class types (std::string, std::string_view, ...): a +// range of const char * would pay strlen twice. +template +concept contiguous_string_range = + std::ranges::contiguous_range && !concepts::optional_type && + !std::is_convertible_v && + std::is_class_v> && + std::is_convertible_v, std::string_view>; +} // namespace internal +#endif + /** * A builder for JSON strings representing documents. This is a low-level * builder that is not meant to be used directly by end-users. Though it @@ -54079,9 +56615,20 @@ class string_builder { simdjson_inline void append(const T &value); #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + // Contiguous arrays of integers, written without a capacity check per element. + template + requires(!require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; + // Contiguous arrays of strings: one capacity check, then quoted escaped + // elements. Same rationale as the integer-array writer. + template + requires (internal::contiguous_string_range && !require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; // Support for range-based appending (std::ranges::view, etc.) template -requires (!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void append(const R &range) noexcept; #endif /** @@ -54223,6 +56770,14 @@ requires (!std::is_convertible::value && !concepts::optiona simdjson_inline void append_static_string() noexcept; #endif +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + /** + * Append an array of integers too long to reserve its worst case at once. + */ + template + void append_long_integer_array(const int_type *data, size_t n) noexcept; +#endif + /** * Grow the buffer to at least desired_capacity bytes. * If the allocation fails, is_valid is set to false. We expect @@ -54247,6 +56802,18 @@ requires (!std::is_convertible::value && !concepts::optiona bool is_valid{true}; }; +namespace internal { +// Appends value as a JSON value. A char is a one-character string, as in +// append_key_value(): string_builder::append(char) appends a raw character. +template +simdjson_inline void append_value(string_builder &b, const T &value) { + b.append(value); +} +simdjson_inline void append_value(string_builder &b, char value) { + b.escape_and_append_with_quotes(value); +} +} // namespace internal + } @@ -54255,21 +56822,12 @@ requires (!std::is_convertible::value && !concepts::optiona #if !SIMDJSON_STATIC_REFLECTION // fallback implementation until we have static reflection +// Defined in json_string_builder-inl.h so number arrays can write straight +// into the destination string (one allocation, no builder copy). template -simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::icelake::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::icelake::builder::string_builder b(initial_capacity); - b.append(z); - std::string s; - auto e = b.move_to(s); - if(e) { return e; } - return s; -} +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::icelake::builder::string_builder::DEFAULT_INITIAL_CAPACITY); template -simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::icelake::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::icelake::builder::string_builder b(initial_capacity); - b.append(z); - return b.move_to(s); -} +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::icelake::builder::string_builder::DEFAULT_INITIAL_CAPACITY); #endif #if SIMDJSON_SUPPORTS_CONCEPTS @@ -54311,7 +56869,7 @@ namespace builder { // included at the point this header is parsed; without these forwards, // name lookup falls back to the wrong outer namespace). namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; simdjson_inline char *write_double(char *p, double v) noexcept; } // namespace internal @@ -54526,7 +57084,7 @@ template simdjson_really_inline void atom_fields(W &w, const T &t, bool &first) { // Per-field block: ensure key+value worst case, then write key + value // through the writer's local pos. For arithmetic fields, the integer - // write happens directly via write_uint_jeaiii on w.ptr+w.pos, so pos + // write happens directly via write_uint on w.ptr+w.pos, so pos // never round-trips through memory. template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) { if constexpr (is_serialized_member(dm)) { @@ -54675,7 +57233,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { "Integers wider than 64 bits are not supported"); // Booleans / floats: defer to string_builder (rare path; keeps writer hot // path free of float-formatter machinery). For integers, write directly - // via jeaiii using local pos. + // via write_uint using local pos. if constexpr (std::is_same_v) { if (t) { if (!w.ensure(4)) return; @@ -54694,7 +57252,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { } } else if constexpr (std::is_unsigned_v) { if (!w.ensure(20)) return; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(t)); w.pos = static_cast(end - w.ptr); } else { @@ -54705,7 +57263,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { U pv = negative ? U(0) - static_cast(t) : static_cast(t); w.ptr[w.pos] = '-'; w.pos += negative; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(pv)); w.pos = static_cast(end - w.ptr); } @@ -55333,7 +57891,7 @@ simdjson_warn_unused simdjson_result extract_fractured_json( /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #define SIMDJSON_GENERIC_STRING_BUILDER_INL_H */ /* amalgamation skipped (editor-only): #include "simdjson/generic/builder/json_string_builder.h" */ -/* amalgamation skipped (editor-only): #include "simdjson/internal/jeaiii.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/write_uint.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/json_escape.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ @@ -55472,7 +58030,7 @@ simdjson_inline void string_builder::clear() noexcept { namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; // Writes v at p, which must have to_chars_buffer_size bytes available, and // returns the end of what was written. @@ -55489,6 +58047,12 @@ simdjson_inline char *write_double(char *p, double v) noexcept { std::memcpy(p, "Infinity", 8); return p + 8; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(p, "null", 4); + return p + 4; + } #endif return simdjson::internal::to_chars(p, nullptr, v); } @@ -55524,7 +58088,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { constexpr size_t max_number_size = 20; if (capacity_check(max_number_size)) { using unsigned_type = typename std::make_unsigned::type; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(static_cast(v))); position = end - buffer_data(); @@ -55543,7 +58107,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { // Branchless: always write '-', advance only if negative. buffer_data()[position] = '-'; position += negative; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(pv)); position = end - buffer_data(); } @@ -55575,6 +58139,13 @@ simdjson_inline void string_builder::append(number_type v) noexcept { } return; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(buffer_data() + position, "null", 4); + position += 4; + return; + } #endif // We could specialize for float. @@ -55688,7 +58259,7 @@ template requires(!require_custom_serialization) simdjson_inline void string_builder::append(const T &opt) { if (opt) { - append(*opt); + internal::append_value(*this, *opt); } else { append_null(); } @@ -55709,9 +58280,213 @@ simdjson_inline void string_builder::append(const T &value) { #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace internal { +// An element of an integer array takes at most its digits, a sign and a comma. +// write_uint writes past the last digit only below 10^4, and then at most +// four bytes in all, which still fits the bound. +template +constexpr size_t max_integer_element_size = + size_t(std::numeric_limits::digits10) + 2 + + (std::is_signed_v ? 1 : 0); + +// Longer arrays reserve their worst case one block at a time, so that an +// array of short numbers does not reserve many times what it writes. +template +constexpr size_t integer_block_size = + (size_t(1) << 20) / max_integer_element_size; + +template +simdjson_inline char *write_integer(char *p, int_type v) noexcept { + if constexpr (std::is_unsigned_v) { + return write_uint(p, static_cast(v)); + } else { + using unsigned_type = std::make_unsigned_t; + const bool negative = v < 0; + unsigned_type pv = negative ? unsigned_type(0) - static_cast(v) + : static_cast(v); + *p = '-'; + p += negative; + return write_uint(p, static_cast(pv)); + } +} +} // namespace internal + +template + requires(!require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + using int_type = std::ranges::range_value_t; + const int_type *data = std::ranges::data(range); + const size_t n = size_t(std::ranges::size(range)); + if (simdjson_unlikely(n > internal::integer_block_size)) { + append_long_integer_array(data, n); + return; + } + if (!capacity_check(2 + n * internal::max_integer_element_size)) { + return; + } + char *p = buffer_data() + position; + *p++ = '['; + for (size_t i = 0; i < n; i++) { + if (i) { + *p++ = ','; + } + p = internal::write_integer(p, data[i]); + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + +template +simdjson_never_inline void +string_builder::append_long_integer_array(const int_type *data, size_t n) noexcept { + constexpr size_t element_size = internal::max_integer_element_size; + constexpr size_t block_size = internal::integer_block_size; + if (!capacity_check(1)) { + return; + } + const size_t start = position; + buffer_data()[position++] = '['; + size_t i = 0; + while (i < n) { + const size_t count = (n - i < block_size) ? n - i : block_size; + size_t upcoming = count * element_size; + if (i == block_size) { + // Reserve for the remaining elements at the average size seen so far, + // so that the buffer is reallocated about once instead of doubling + // through many sizes. + size_t average = (position - start) / i + 1; + average = average < element_size ? average : element_size; + if (n - i <= (std::numeric_limits::max)() / average) { + const size_t estimate = (n - i) * average; + upcoming = estimate > upcoming ? estimate : upcoming; + } + } + if (!capacity_check(upcoming)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + for (const size_t stop = i + count; i < stop; i++) { + p = internal::write_integer(p, data[i]); + *p++ = ','; + } + position = size_t(p - buffer_data()); + } + // The closing bracket replaces the comma after the last element. + buffer_data()[position - 1] = ']'; +} + +namespace internal { +// Cold path of the string-array writer: the element may not fit its +// worst-case escaped size in the remaining capacity. Writes the element and +// returns the new write pointer, or nullptr if the buffer could not grow. +simdjson_never_inline char *append_quoted_element_slow(string_builder &b, + std::string_view sv, + bool first) noexcept { + auto reserve = [&b](size_t n) { + const size_t pos = b.unsafe_position(); + const size_t cap = b.unsafe_capacity(); + if (n <= cap - pos) { + return true; + } + if (pos + n < pos) { + return false; + } + return b.unsafe_grow((std::max)(cap * 2, pos + n)); + }; + if (sv.size() > 512) { + if (!reserve(6 * sv.size() + 4)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + if (!first) { + *p++ = ','; + } + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + return p; + } + // Escape into a stack buffer first so that we grow by the exact size. + simdjson_indeterminate char tmp[3 + 6 * 512]; + char *tp = tmp; + if (!first) { + *tp++ = ','; + } + *tp++ = '"'; + tp += write_string_escaped(sv, tp); + *tp++ = '"'; + const size_t n = size_t(tp - tmp); + // One more byte for the closing bracket. + if (!reserve(n + 1)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + std::memcpy(p, tmp, n); + return p + n; +} +} // namespace internal + +template + requires (internal::contiguous_string_range && !require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + // Reserve the unescaped size (brackets, commas, quotes, bytes) plus 1/16 + // for escapes. A 6x worst-case reservation made a fresh builder allocate + // several times the output; an exact one made the first escape double + // the buffer. + size_t bytes = 2; + for (const auto &item : range) { + const std::string_view sv = item; + if (sv.size() > ((std::numeric_limits::max)() - 4) / 6 || + sv.size() > (std::numeric_limits::max)() - bytes - 3) { + set_valid(false); + return; + } + bytes += 3 + sv.size(); + } + const size_t slack = bytes / 16; + if (bytes > (std::numeric_limits::max)() - slack) { + set_valid(false); + return; + } + if (!capacity_check(bytes + slack)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + *p++ = '['; + bool first = true; + for (const auto &item : range) { + const std::string_view sv = item; + const size_t off = size_t(p - buffer_data()); + // Comma, two quotes, up to 6 bytes per input byte, closing bracket. + if (simdjson_unlikely(6 * sv.size() + 4 > capacity - off)) { + position = off; + p = internal::append_quoted_element_slow(*this, sv, first); + if (p == nullptr) { + set_valid(false); + return; + } + first = false; + continue; + } + if (!first) { + *p++ = ','; + } + first = false; + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + // Support for range-based appending (std::ranges::view, etc.) template - requires(!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void string_builder::append(const R &range) noexcept { auto it = std::ranges::begin(range); auto end = std::ranges::end(range); @@ -55740,13 +58515,13 @@ simdjson_inline void string_builder::append(const R &range) noexcept { } // Append first item without leading comma - append(*it); + internal::append_value(*this, *it); ++it; // Append remaining items with preceding commas for (; it != end; ++it) { append_comma(); - append(*it); + internal::append_value(*this, *it); } end_array(); } @@ -55946,6 +58721,175 @@ string_builder::append_key_value() noexcept { } // namespace icelake } // namespace simdjson + +#if !SIMDJSON_STATIC_REFLECTION +namespace simdjson { + +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace builder_to_json_detail { +// Concepts, not constexpr bools: a conjunction of concepts stops at the +// first unsatisfied one, so range_value_t is never formed for a non-range. +template +concept contiguous_number_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !require_custom_serialization; +template +concept contiguous_int_array = + contiguous_number_array && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; +template +concept contiguous_float_array = + contiguous_number_array && + std::is_floating_point_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t); + +// Most bytes one element writes, the comma before it included. A double +// takes at most 24 characters (-d.dddddddddddddddde-308). +template +constexpr size_t max_element_size() { + if constexpr (std::is_floating_point_v) { + return 24 + 1; + } else { + return size_t(std::numeric_limits::digits10) + 1 + std::is_signed_v + 1; + } +} +// The number writers may write scratch bytes past the end of the number. +constexpr size_t write_slack = simdjson::internal::to_chars_buffer_size; +// Arrays whose bound fits are written on the stack, then copied once. +constexpr size_t stack_buffer_size = 1024; + +template +simdjson_inline char *write_element(char *p, T v) noexcept { + if constexpr (std::is_floating_point_v) { + return simdjson::icelake::builder::internal::write_double(p, double(v)); + } else if constexpr (std::is_unsigned_v) { + return simdjson::internal::write_uint(p, static_cast(v)); + } else { + using U = std::make_unsigned_t; + const bool negative = v < 0; + U pv = negative ? U(0) - static_cast(v) : static_cast(v); + *p = '-'; + p += negative; + return simdjson::internal::write_uint(p, static_cast(pv)); + } +} + +template +simdjson_inline char *write_array(char *p, const T *data, size_t n) noexcept { + *p++ = '['; + if (n) { + p = write_element(p, data[0]); + for (size_t i = 1; i < n; i++) { + *p++ = ','; + p = write_element(p, data[i]); + } + } + *p++ = ']'; + return p; +} + +// Not simdjson_inline: MSVC cannot force-inline a function with a try block (C4714). +inline bool assign_bytes(std::string &s, const char *data, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + s.assign(data, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + // Without exceptions, a failed allocation terminates the program. + s.assign(data, n); +#endif + return true; +} + +inline bool resize_for_direct_write(std::string &s, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + simdjson::icelake::builder::internal::resize_uninitialized(s, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + simdjson::icelake::builder::internal::resize_uninitialized(s, n); +#endif + return true; +} + +// A result that fills at most half of the allocation is copied out, as in +// string_builder::move_to. On failure s keeps the larger buffer. +simdjson_never_inline void shrink_to_size(std::string &s) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + std::string(s).swap(s); + } catch (...) { // std::bad_alloc + } +#else + std::string(s).swap(s); +#endif +} + +template +simdjson_warn_unused error_code to_json_array(const T *data, size_t n, std::string &s) noexcept { + constexpr size_t per = max_element_size(); + if (simdjson_unlikely(n > (size_t(-1) - 2 - write_slack) / per)) { + return MEMALLOC; + } + const size_t bound = n * per + 2 + write_slack; + if (bound <= stack_buffer_size) { + simdjson_indeterminate char buffer[stack_buffer_size]; + char *end = write_array(buffer, data, n); + return assign_bytes(s, buffer, size_t(end - buffer)) ? SUCCESS : MEMALLOC; + } + const size_t old_capacity = s.capacity(); + if (!resize_for_direct_write(s, bound)) { + return MEMALLOC; + } + char *begin = &s[0]; + const size_t used = size_t(write_array(begin, data, n) - begin); + s.resize(used); + // A string that could already hold the result is being reused: keep its + // buffer so the next call does not allocate again. + if (old_capacity < used && used <= s.capacity() / 2) { + shrink_to_size(s); + } + return SUCCESS; +} +} // namespace builder_to_json_detail +#endif // SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + +template +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity) { +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + if constexpr (builder_to_json_detail::contiguous_int_array || + builder_to_json_detail::contiguous_float_array) { + (void)initial_capacity; + return builder_to_json_detail::to_json_array(std::ranges::data(z), size_t(std::ranges::size(z)), s); + } else +#endif + { + simdjson::icelake::builder::string_builder b(initial_capacity); + simdjson::icelake::builder::internal::append_value(b, z); + return b.move_to(s); + } +} + +template +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity) { + std::string s; + auto e = to_json(z, s, initial_capacity); + if (e) { return e; } + return s; +} + +} // namespace simdjson +#endif // !SIMDJSON_STATIC_REFLECTION + #endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H /* end file simdjson/generic/builder/json_string_builder-inl.h for icelake */ @@ -56160,6 +59104,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/ppc64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/ppc64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -56175,7 +59120,6 @@ namespace ppc64 { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; @@ -56187,9 +59131,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars val = bswap64(val); #endif #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -56515,6 +59457,14 @@ template <> struct simd8 : base8_numeric { // Unsigned bytes template <> struct simd8 : base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} @@ -56829,6 +59779,36 @@ namespace builder { using simdjson::internal::escape_best::write_string_escaped; +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +/** + * A contiguous, sized range of integers that string_builder serializes as a + * JSON array of numbers in one pass. Booleans and character types are excluded, + * and so are integers wider than 64 bits. In C++26, std::optional is a + * contiguous range: it is excluded so that the optional overload is chosen. + */ +template +concept integer_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !concepts::optional_type && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; + +namespace internal { +// Elements must be class types (std::string, std::string_view, ...): a +// range of const char * would pay strlen twice. +template +concept contiguous_string_range = + std::ranges::contiguous_range && !concepts::optional_type && + !std::is_convertible_v && + std::is_class_v> && + std::is_convertible_v, std::string_view>; +} // namespace internal +#endif + /** * A builder for JSON strings representing documents. This is a low-level * builder that is not meant to be used directly by end-users. Though it @@ -56982,9 +59962,20 @@ class string_builder { simdjson_inline void append(const T &value); #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + // Contiguous arrays of integers, written without a capacity check per element. + template + requires(!require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; + // Contiguous arrays of strings: one capacity check, then quoted escaped + // elements. Same rationale as the integer-array writer. + template + requires (internal::contiguous_string_range && !require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; // Support for range-based appending (std::ranges::view, etc.) template -requires (!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void append(const R &range) noexcept; #endif /** @@ -57126,6 +60117,14 @@ requires (!std::is_convertible::value && !concepts::optiona simdjson_inline void append_static_string() noexcept; #endif +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + /** + * Append an array of integers too long to reserve its worst case at once. + */ + template + void append_long_integer_array(const int_type *data, size_t n) noexcept; +#endif + /** * Grow the buffer to at least desired_capacity bytes. * If the allocation fails, is_valid is set to false. We expect @@ -57150,6 +60149,18 @@ requires (!std::is_convertible::value && !concepts::optiona bool is_valid{true}; }; +namespace internal { +// Appends value as a JSON value. A char is a one-character string, as in +// append_key_value(): string_builder::append(char) appends a raw character. +template +simdjson_inline void append_value(string_builder &b, const T &value) { + b.append(value); +} +simdjson_inline void append_value(string_builder &b, char value) { + b.escape_and_append_with_quotes(value); +} +} // namespace internal + } @@ -57158,21 +60169,12 @@ requires (!std::is_convertible::value && !concepts::optiona #if !SIMDJSON_STATIC_REFLECTION // fallback implementation until we have static reflection +// Defined in json_string_builder-inl.h so number arrays can write straight +// into the destination string (one allocation, no builder copy). template -simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::ppc64::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::ppc64::builder::string_builder b(initial_capacity); - b.append(z); - std::string s; - auto e = b.move_to(s); - if(e) { return e; } - return s; -} +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::ppc64::builder::string_builder::DEFAULT_INITIAL_CAPACITY); template -simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::ppc64::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::ppc64::builder::string_builder b(initial_capacity); - b.append(z); - return b.move_to(s); -} +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::ppc64::builder::string_builder::DEFAULT_INITIAL_CAPACITY); #endif #if SIMDJSON_SUPPORTS_CONCEPTS @@ -57214,7 +60216,7 @@ namespace builder { // included at the point this header is parsed; without these forwards, // name lookup falls back to the wrong outer namespace). namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; simdjson_inline char *write_double(char *p, double v) noexcept; } // namespace internal @@ -57429,7 +60431,7 @@ template simdjson_really_inline void atom_fields(W &w, const T &t, bool &first) { // Per-field block: ensure key+value worst case, then write key + value // through the writer's local pos. For arithmetic fields, the integer - // write happens directly via write_uint_jeaiii on w.ptr+w.pos, so pos + // write happens directly via write_uint on w.ptr+w.pos, so pos // never round-trips through memory. template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) { if constexpr (is_serialized_member(dm)) { @@ -57578,7 +60580,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { "Integers wider than 64 bits are not supported"); // Booleans / floats: defer to string_builder (rare path; keeps writer hot // path free of float-formatter machinery). For integers, write directly - // via jeaiii using local pos. + // via write_uint using local pos. if constexpr (std::is_same_v) { if (t) { if (!w.ensure(4)) return; @@ -57597,7 +60599,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { } } else if constexpr (std::is_unsigned_v) { if (!w.ensure(20)) return; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(t)); w.pos = static_cast(end - w.ptr); } else { @@ -57608,7 +60610,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { U pv = negative ? U(0) - static_cast(t) : static_cast(t); w.ptr[w.pos] = '-'; w.pos += negative; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(pv)); w.pos = static_cast(end - w.ptr); } @@ -58236,7 +61238,7 @@ simdjson_warn_unused simdjson_result extract_fractured_json( /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #define SIMDJSON_GENERIC_STRING_BUILDER_INL_H */ /* amalgamation skipped (editor-only): #include "simdjson/generic/builder/json_string_builder.h" */ -/* amalgamation skipped (editor-only): #include "simdjson/internal/jeaiii.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/write_uint.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/json_escape.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ @@ -58375,7 +61377,7 @@ simdjson_inline void string_builder::clear() noexcept { namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; // Writes v at p, which must have to_chars_buffer_size bytes available, and // returns the end of what was written. @@ -58392,6 +61394,12 @@ simdjson_inline char *write_double(char *p, double v) noexcept { std::memcpy(p, "Infinity", 8); return p + 8; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(p, "null", 4); + return p + 4; + } #endif return simdjson::internal::to_chars(p, nullptr, v); } @@ -58427,7 +61435,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { constexpr size_t max_number_size = 20; if (capacity_check(max_number_size)) { using unsigned_type = typename std::make_unsigned::type; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(static_cast(v))); position = end - buffer_data(); @@ -58446,7 +61454,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { // Branchless: always write '-', advance only if negative. buffer_data()[position] = '-'; position += negative; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(pv)); position = end - buffer_data(); } @@ -58478,6 +61486,13 @@ simdjson_inline void string_builder::append(number_type v) noexcept { } return; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(buffer_data() + position, "null", 4); + position += 4; + return; + } #endif // We could specialize for float. @@ -58591,7 +61606,7 @@ template requires(!require_custom_serialization) simdjson_inline void string_builder::append(const T &opt) { if (opt) { - append(*opt); + internal::append_value(*this, *opt); } else { append_null(); } @@ -58612,9 +61627,213 @@ simdjson_inline void string_builder::append(const T &value) { #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace internal { +// An element of an integer array takes at most its digits, a sign and a comma. +// write_uint writes past the last digit only below 10^4, and then at most +// four bytes in all, which still fits the bound. +template +constexpr size_t max_integer_element_size = + size_t(std::numeric_limits::digits10) + 2 + + (std::is_signed_v ? 1 : 0); + +// Longer arrays reserve their worst case one block at a time, so that an +// array of short numbers does not reserve many times what it writes. +template +constexpr size_t integer_block_size = + (size_t(1) << 20) / max_integer_element_size; + +template +simdjson_inline char *write_integer(char *p, int_type v) noexcept { + if constexpr (std::is_unsigned_v) { + return write_uint(p, static_cast(v)); + } else { + using unsigned_type = std::make_unsigned_t; + const bool negative = v < 0; + unsigned_type pv = negative ? unsigned_type(0) - static_cast(v) + : static_cast(v); + *p = '-'; + p += negative; + return write_uint(p, static_cast(pv)); + } +} +} // namespace internal + +template + requires(!require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + using int_type = std::ranges::range_value_t; + const int_type *data = std::ranges::data(range); + const size_t n = size_t(std::ranges::size(range)); + if (simdjson_unlikely(n > internal::integer_block_size)) { + append_long_integer_array(data, n); + return; + } + if (!capacity_check(2 + n * internal::max_integer_element_size)) { + return; + } + char *p = buffer_data() + position; + *p++ = '['; + for (size_t i = 0; i < n; i++) { + if (i) { + *p++ = ','; + } + p = internal::write_integer(p, data[i]); + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + +template +simdjson_never_inline void +string_builder::append_long_integer_array(const int_type *data, size_t n) noexcept { + constexpr size_t element_size = internal::max_integer_element_size; + constexpr size_t block_size = internal::integer_block_size; + if (!capacity_check(1)) { + return; + } + const size_t start = position; + buffer_data()[position++] = '['; + size_t i = 0; + while (i < n) { + const size_t count = (n - i < block_size) ? n - i : block_size; + size_t upcoming = count * element_size; + if (i == block_size) { + // Reserve for the remaining elements at the average size seen so far, + // so that the buffer is reallocated about once instead of doubling + // through many sizes. + size_t average = (position - start) / i + 1; + average = average < element_size ? average : element_size; + if (n - i <= (std::numeric_limits::max)() / average) { + const size_t estimate = (n - i) * average; + upcoming = estimate > upcoming ? estimate : upcoming; + } + } + if (!capacity_check(upcoming)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + for (const size_t stop = i + count; i < stop; i++) { + p = internal::write_integer(p, data[i]); + *p++ = ','; + } + position = size_t(p - buffer_data()); + } + // The closing bracket replaces the comma after the last element. + buffer_data()[position - 1] = ']'; +} + +namespace internal { +// Cold path of the string-array writer: the element may not fit its +// worst-case escaped size in the remaining capacity. Writes the element and +// returns the new write pointer, or nullptr if the buffer could not grow. +simdjson_never_inline char *append_quoted_element_slow(string_builder &b, + std::string_view sv, + bool first) noexcept { + auto reserve = [&b](size_t n) { + const size_t pos = b.unsafe_position(); + const size_t cap = b.unsafe_capacity(); + if (n <= cap - pos) { + return true; + } + if (pos + n < pos) { + return false; + } + return b.unsafe_grow((std::max)(cap * 2, pos + n)); + }; + if (sv.size() > 512) { + if (!reserve(6 * sv.size() + 4)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + if (!first) { + *p++ = ','; + } + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + return p; + } + // Escape into a stack buffer first so that we grow by the exact size. + simdjson_indeterminate char tmp[3 + 6 * 512]; + char *tp = tmp; + if (!first) { + *tp++ = ','; + } + *tp++ = '"'; + tp += write_string_escaped(sv, tp); + *tp++ = '"'; + const size_t n = size_t(tp - tmp); + // One more byte for the closing bracket. + if (!reserve(n + 1)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + std::memcpy(p, tmp, n); + return p + n; +} +} // namespace internal + +template + requires (internal::contiguous_string_range && !require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + // Reserve the unescaped size (brackets, commas, quotes, bytes) plus 1/16 + // for escapes. A 6x worst-case reservation made a fresh builder allocate + // several times the output; an exact one made the first escape double + // the buffer. + size_t bytes = 2; + for (const auto &item : range) { + const std::string_view sv = item; + if (sv.size() > ((std::numeric_limits::max)() - 4) / 6 || + sv.size() > (std::numeric_limits::max)() - bytes - 3) { + set_valid(false); + return; + } + bytes += 3 + sv.size(); + } + const size_t slack = bytes / 16; + if (bytes > (std::numeric_limits::max)() - slack) { + set_valid(false); + return; + } + if (!capacity_check(bytes + slack)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + *p++ = '['; + bool first = true; + for (const auto &item : range) { + const std::string_view sv = item; + const size_t off = size_t(p - buffer_data()); + // Comma, two quotes, up to 6 bytes per input byte, closing bracket. + if (simdjson_unlikely(6 * sv.size() + 4 > capacity - off)) { + position = off; + p = internal::append_quoted_element_slow(*this, sv, first); + if (p == nullptr) { + set_valid(false); + return; + } + first = false; + continue; + } + if (!first) { + *p++ = ','; + } + first = false; + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + // Support for range-based appending (std::ranges::view, etc.) template - requires(!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void string_builder::append(const R &range) noexcept { auto it = std::ranges::begin(range); auto end = std::ranges::end(range); @@ -58643,13 +61862,13 @@ simdjson_inline void string_builder::append(const R &range) noexcept { } // Append first item without leading comma - append(*it); + internal::append_value(*this, *it); ++it; // Append remaining items with preceding commas for (; it != end; ++it) { append_comma(); - append(*it); + internal::append_value(*this, *it); } end_array(); } @@ -58849,6 +62068,175 @@ string_builder::append_key_value() noexcept { } // namespace ppc64 } // namespace simdjson + +#if !SIMDJSON_STATIC_REFLECTION +namespace simdjson { + +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace builder_to_json_detail { +// Concepts, not constexpr bools: a conjunction of concepts stops at the +// first unsatisfied one, so range_value_t is never formed for a non-range. +template +concept contiguous_number_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !require_custom_serialization; +template +concept contiguous_int_array = + contiguous_number_array && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; +template +concept contiguous_float_array = + contiguous_number_array && + std::is_floating_point_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t); + +// Most bytes one element writes, the comma before it included. A double +// takes at most 24 characters (-d.dddddddddddddddde-308). +template +constexpr size_t max_element_size() { + if constexpr (std::is_floating_point_v) { + return 24 + 1; + } else { + return size_t(std::numeric_limits::digits10) + 1 + std::is_signed_v + 1; + } +} +// The number writers may write scratch bytes past the end of the number. +constexpr size_t write_slack = simdjson::internal::to_chars_buffer_size; +// Arrays whose bound fits are written on the stack, then copied once. +constexpr size_t stack_buffer_size = 1024; + +template +simdjson_inline char *write_element(char *p, T v) noexcept { + if constexpr (std::is_floating_point_v) { + return simdjson::ppc64::builder::internal::write_double(p, double(v)); + } else if constexpr (std::is_unsigned_v) { + return simdjson::internal::write_uint(p, static_cast(v)); + } else { + using U = std::make_unsigned_t; + const bool negative = v < 0; + U pv = negative ? U(0) - static_cast(v) : static_cast(v); + *p = '-'; + p += negative; + return simdjson::internal::write_uint(p, static_cast(pv)); + } +} + +template +simdjson_inline char *write_array(char *p, const T *data, size_t n) noexcept { + *p++ = '['; + if (n) { + p = write_element(p, data[0]); + for (size_t i = 1; i < n; i++) { + *p++ = ','; + p = write_element(p, data[i]); + } + } + *p++ = ']'; + return p; +} + +// Not simdjson_inline: MSVC cannot force-inline a function with a try block (C4714). +inline bool assign_bytes(std::string &s, const char *data, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + s.assign(data, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + // Without exceptions, a failed allocation terminates the program. + s.assign(data, n); +#endif + return true; +} + +inline bool resize_for_direct_write(std::string &s, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + simdjson::ppc64::builder::internal::resize_uninitialized(s, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + simdjson::ppc64::builder::internal::resize_uninitialized(s, n); +#endif + return true; +} + +// A result that fills at most half of the allocation is copied out, as in +// string_builder::move_to. On failure s keeps the larger buffer. +simdjson_never_inline void shrink_to_size(std::string &s) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + std::string(s).swap(s); + } catch (...) { // std::bad_alloc + } +#else + std::string(s).swap(s); +#endif +} + +template +simdjson_warn_unused error_code to_json_array(const T *data, size_t n, std::string &s) noexcept { + constexpr size_t per = max_element_size(); + if (simdjson_unlikely(n > (size_t(-1) - 2 - write_slack) / per)) { + return MEMALLOC; + } + const size_t bound = n * per + 2 + write_slack; + if (bound <= stack_buffer_size) { + simdjson_indeterminate char buffer[stack_buffer_size]; + char *end = write_array(buffer, data, n); + return assign_bytes(s, buffer, size_t(end - buffer)) ? SUCCESS : MEMALLOC; + } + const size_t old_capacity = s.capacity(); + if (!resize_for_direct_write(s, bound)) { + return MEMALLOC; + } + char *begin = &s[0]; + const size_t used = size_t(write_array(begin, data, n) - begin); + s.resize(used); + // A string that could already hold the result is being reused: keep its + // buffer so the next call does not allocate again. + if (old_capacity < used && used <= s.capacity() / 2) { + shrink_to_size(s); + } + return SUCCESS; +} +} // namespace builder_to_json_detail +#endif // SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + +template +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity) { +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + if constexpr (builder_to_json_detail::contiguous_int_array || + builder_to_json_detail::contiguous_float_array) { + (void)initial_capacity; + return builder_to_json_detail::to_json_array(std::ranges::data(z), size_t(std::ranges::size(z)), s); + } else +#endif + { + simdjson::ppc64::builder::string_builder b(initial_capacity); + simdjson::ppc64::builder::internal::append_value(b, z); + return b.move_to(s); + } +} + +template +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity) { + std::string s; + auto e = to_json(z, s, initial_capacity); + if (e) { return e; } + return s; +} + +} // namespace simdjson +#endif // !SIMDJSON_STATIC_REFLECTION + #endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H /* end file simdjson/generic/builder/json_string_builder-inl.h for ppc64 */ @@ -59187,6 +62575,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -59381,6 +62770,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -59606,6 +63013,7 @@ simdjson_inline long long int count_ones(uint64_t input_num) { /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -59800,6 +63208,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -60037,6 +63463,36 @@ namespace builder { using simdjson::internal::escape_best::write_string_escaped; +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +/** + * A contiguous, sized range of integers that string_builder serializes as a + * JSON array of numbers in one pass. Booleans and character types are excluded, + * and so are integers wider than 64 bits. In C++26, std::optional is a + * contiguous range: it is excluded so that the optional overload is chosen. + */ +template +concept integer_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !concepts::optional_type && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; + +namespace internal { +// Elements must be class types (std::string, std::string_view, ...): a +// range of const char * would pay strlen twice. +template +concept contiguous_string_range = + std::ranges::contiguous_range && !concepts::optional_type && + !std::is_convertible_v && + std::is_class_v> && + std::is_convertible_v, std::string_view>; +} // namespace internal +#endif + /** * A builder for JSON strings representing documents. This is a low-level * builder that is not meant to be used directly by end-users. Though it @@ -60190,9 +63646,20 @@ class string_builder { simdjson_inline void append(const T &value); #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + // Contiguous arrays of integers, written without a capacity check per element. + template + requires(!require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; + // Contiguous arrays of strings: one capacity check, then quoted escaped + // elements. Same rationale as the integer-array writer. + template + requires (internal::contiguous_string_range && !require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; // Support for range-based appending (std::ranges::view, etc.) template -requires (!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void append(const R &range) noexcept; #endif /** @@ -60334,6 +63801,14 @@ requires (!std::is_convertible::value && !concepts::optiona simdjson_inline void append_static_string() noexcept; #endif +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + /** + * Append an array of integers too long to reserve its worst case at once. + */ + template + void append_long_integer_array(const int_type *data, size_t n) noexcept; +#endif + /** * Grow the buffer to at least desired_capacity bytes. * If the allocation fails, is_valid is set to false. We expect @@ -60358,6 +63833,18 @@ requires (!std::is_convertible::value && !concepts::optiona bool is_valid{true}; }; +namespace internal { +// Appends value as a JSON value. A char is a one-character string, as in +// append_key_value(): string_builder::append(char) appends a raw character. +template +simdjson_inline void append_value(string_builder &b, const T &value) { + b.append(value); +} +simdjson_inline void append_value(string_builder &b, char value) { + b.escape_and_append_with_quotes(value); +} +} // namespace internal + } @@ -60366,21 +63853,12 @@ requires (!std::is_convertible::value && !concepts::optiona #if !SIMDJSON_STATIC_REFLECTION // fallback implementation until we have static reflection +// Defined in json_string_builder-inl.h so number arrays can write straight +// into the destination string (one allocation, no builder copy). template -simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::westmere::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::westmere::builder::string_builder b(initial_capacity); - b.append(z); - std::string s; - auto e = b.move_to(s); - if(e) { return e; } - return s; -} +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::westmere::builder::string_builder::DEFAULT_INITIAL_CAPACITY); template -simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::westmere::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::westmere::builder::string_builder b(initial_capacity); - b.append(z); - return b.move_to(s); -} +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::westmere::builder::string_builder::DEFAULT_INITIAL_CAPACITY); #endif #if SIMDJSON_SUPPORTS_CONCEPTS @@ -60422,7 +63900,7 @@ namespace builder { // included at the point this header is parsed; without these forwards, // name lookup falls back to the wrong outer namespace). namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; simdjson_inline char *write_double(char *p, double v) noexcept; } // namespace internal @@ -60637,7 +64115,7 @@ template simdjson_really_inline void atom_fields(W &w, const T &t, bool &first) { // Per-field block: ensure key+value worst case, then write key + value // through the writer's local pos. For arithmetic fields, the integer - // write happens directly via write_uint_jeaiii on w.ptr+w.pos, so pos + // write happens directly via write_uint on w.ptr+w.pos, so pos // never round-trips through memory. template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) { if constexpr (is_serialized_member(dm)) { @@ -60786,7 +64264,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { "Integers wider than 64 bits are not supported"); // Booleans / floats: defer to string_builder (rare path; keeps writer hot // path free of float-formatter machinery). For integers, write directly - // via jeaiii using local pos. + // via write_uint using local pos. if constexpr (std::is_same_v) { if (t) { if (!w.ensure(4)) return; @@ -60805,7 +64283,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { } } else if constexpr (std::is_unsigned_v) { if (!w.ensure(20)) return; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(t)); w.pos = static_cast(end - w.ptr); } else { @@ -60816,7 +64294,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { U pv = negative ? U(0) - static_cast(t) : static_cast(t); w.ptr[w.pos] = '-'; w.pos += negative; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(pv)); w.pos = static_cast(end - w.ptr); } @@ -61444,7 +64922,7 @@ simdjson_warn_unused simdjson_result extract_fractured_json( /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #define SIMDJSON_GENERIC_STRING_BUILDER_INL_H */ /* amalgamation skipped (editor-only): #include "simdjson/generic/builder/json_string_builder.h" */ -/* amalgamation skipped (editor-only): #include "simdjson/internal/jeaiii.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/write_uint.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/json_escape.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ @@ -61583,7 +65061,7 @@ simdjson_inline void string_builder::clear() noexcept { namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; // Writes v at p, which must have to_chars_buffer_size bytes available, and // returns the end of what was written. @@ -61600,6 +65078,12 @@ simdjson_inline char *write_double(char *p, double v) noexcept { std::memcpy(p, "Infinity", 8); return p + 8; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(p, "null", 4); + return p + 4; + } #endif return simdjson::internal::to_chars(p, nullptr, v); } @@ -61635,7 +65119,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { constexpr size_t max_number_size = 20; if (capacity_check(max_number_size)) { using unsigned_type = typename std::make_unsigned::type; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(static_cast(v))); position = end - buffer_data(); @@ -61654,7 +65138,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { // Branchless: always write '-', advance only if negative. buffer_data()[position] = '-'; position += negative; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(pv)); position = end - buffer_data(); } @@ -61686,6 +65170,13 @@ simdjson_inline void string_builder::append(number_type v) noexcept { } return; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(buffer_data() + position, "null", 4); + position += 4; + return; + } #endif // We could specialize for float. @@ -61799,7 +65290,7 @@ template requires(!require_custom_serialization) simdjson_inline void string_builder::append(const T &opt) { if (opt) { - append(*opt); + internal::append_value(*this, *opt); } else { append_null(); } @@ -61820,9 +65311,213 @@ simdjson_inline void string_builder::append(const T &value) { #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace internal { +// An element of an integer array takes at most its digits, a sign and a comma. +// write_uint writes past the last digit only below 10^4, and then at most +// four bytes in all, which still fits the bound. +template +constexpr size_t max_integer_element_size = + size_t(std::numeric_limits::digits10) + 2 + + (std::is_signed_v ? 1 : 0); + +// Longer arrays reserve their worst case one block at a time, so that an +// array of short numbers does not reserve many times what it writes. +template +constexpr size_t integer_block_size = + (size_t(1) << 20) / max_integer_element_size; + +template +simdjson_inline char *write_integer(char *p, int_type v) noexcept { + if constexpr (std::is_unsigned_v) { + return write_uint(p, static_cast(v)); + } else { + using unsigned_type = std::make_unsigned_t; + const bool negative = v < 0; + unsigned_type pv = negative ? unsigned_type(0) - static_cast(v) + : static_cast(v); + *p = '-'; + p += negative; + return write_uint(p, static_cast(pv)); + } +} +} // namespace internal + +template + requires(!require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + using int_type = std::ranges::range_value_t; + const int_type *data = std::ranges::data(range); + const size_t n = size_t(std::ranges::size(range)); + if (simdjson_unlikely(n > internal::integer_block_size)) { + append_long_integer_array(data, n); + return; + } + if (!capacity_check(2 + n * internal::max_integer_element_size)) { + return; + } + char *p = buffer_data() + position; + *p++ = '['; + for (size_t i = 0; i < n; i++) { + if (i) { + *p++ = ','; + } + p = internal::write_integer(p, data[i]); + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + +template +simdjson_never_inline void +string_builder::append_long_integer_array(const int_type *data, size_t n) noexcept { + constexpr size_t element_size = internal::max_integer_element_size; + constexpr size_t block_size = internal::integer_block_size; + if (!capacity_check(1)) { + return; + } + const size_t start = position; + buffer_data()[position++] = '['; + size_t i = 0; + while (i < n) { + const size_t count = (n - i < block_size) ? n - i : block_size; + size_t upcoming = count * element_size; + if (i == block_size) { + // Reserve for the remaining elements at the average size seen so far, + // so that the buffer is reallocated about once instead of doubling + // through many sizes. + size_t average = (position - start) / i + 1; + average = average < element_size ? average : element_size; + if (n - i <= (std::numeric_limits::max)() / average) { + const size_t estimate = (n - i) * average; + upcoming = estimate > upcoming ? estimate : upcoming; + } + } + if (!capacity_check(upcoming)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + for (const size_t stop = i + count; i < stop; i++) { + p = internal::write_integer(p, data[i]); + *p++ = ','; + } + position = size_t(p - buffer_data()); + } + // The closing bracket replaces the comma after the last element. + buffer_data()[position - 1] = ']'; +} + +namespace internal { +// Cold path of the string-array writer: the element may not fit its +// worst-case escaped size in the remaining capacity. Writes the element and +// returns the new write pointer, or nullptr if the buffer could not grow. +simdjson_never_inline char *append_quoted_element_slow(string_builder &b, + std::string_view sv, + bool first) noexcept { + auto reserve = [&b](size_t n) { + const size_t pos = b.unsafe_position(); + const size_t cap = b.unsafe_capacity(); + if (n <= cap - pos) { + return true; + } + if (pos + n < pos) { + return false; + } + return b.unsafe_grow((std::max)(cap * 2, pos + n)); + }; + if (sv.size() > 512) { + if (!reserve(6 * sv.size() + 4)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + if (!first) { + *p++ = ','; + } + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + return p; + } + // Escape into a stack buffer first so that we grow by the exact size. + simdjson_indeterminate char tmp[3 + 6 * 512]; + char *tp = tmp; + if (!first) { + *tp++ = ','; + } + *tp++ = '"'; + tp += write_string_escaped(sv, tp); + *tp++ = '"'; + const size_t n = size_t(tp - tmp); + // One more byte for the closing bracket. + if (!reserve(n + 1)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + std::memcpy(p, tmp, n); + return p + n; +} +} // namespace internal + +template + requires (internal::contiguous_string_range && !require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + // Reserve the unescaped size (brackets, commas, quotes, bytes) plus 1/16 + // for escapes. A 6x worst-case reservation made a fresh builder allocate + // several times the output; an exact one made the first escape double + // the buffer. + size_t bytes = 2; + for (const auto &item : range) { + const std::string_view sv = item; + if (sv.size() > ((std::numeric_limits::max)() - 4) / 6 || + sv.size() > (std::numeric_limits::max)() - bytes - 3) { + set_valid(false); + return; + } + bytes += 3 + sv.size(); + } + const size_t slack = bytes / 16; + if (bytes > (std::numeric_limits::max)() - slack) { + set_valid(false); + return; + } + if (!capacity_check(bytes + slack)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + *p++ = '['; + bool first = true; + for (const auto &item : range) { + const std::string_view sv = item; + const size_t off = size_t(p - buffer_data()); + // Comma, two quotes, up to 6 bytes per input byte, closing bracket. + if (simdjson_unlikely(6 * sv.size() + 4 > capacity - off)) { + position = off; + p = internal::append_quoted_element_slow(*this, sv, first); + if (p == nullptr) { + set_valid(false); + return; + } + first = false; + continue; + } + if (!first) { + *p++ = ','; + } + first = false; + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + // Support for range-based appending (std::ranges::view, etc.) template - requires(!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void string_builder::append(const R &range) noexcept { auto it = std::ranges::begin(range); auto end = std::ranges::end(range); @@ -61851,13 +65546,13 @@ simdjson_inline void string_builder::append(const R &range) noexcept { } // Append first item without leading comma - append(*it); + internal::append_value(*this, *it); ++it; // Append remaining items with preceding commas for (; it != end; ++it) { append_comma(); - append(*it); + internal::append_value(*this, *it); } end_array(); } @@ -62057,6 +65752,175 @@ string_builder::append_key_value() noexcept { } // namespace westmere } // namespace simdjson + +#if !SIMDJSON_STATIC_REFLECTION +namespace simdjson { + +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace builder_to_json_detail { +// Concepts, not constexpr bools: a conjunction of concepts stops at the +// first unsatisfied one, so range_value_t is never formed for a non-range. +template +concept contiguous_number_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !require_custom_serialization; +template +concept contiguous_int_array = + contiguous_number_array && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; +template +concept contiguous_float_array = + contiguous_number_array && + std::is_floating_point_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t); + +// Most bytes one element writes, the comma before it included. A double +// takes at most 24 characters (-d.dddddddddddddddde-308). +template +constexpr size_t max_element_size() { + if constexpr (std::is_floating_point_v) { + return 24 + 1; + } else { + return size_t(std::numeric_limits::digits10) + 1 + std::is_signed_v + 1; + } +} +// The number writers may write scratch bytes past the end of the number. +constexpr size_t write_slack = simdjson::internal::to_chars_buffer_size; +// Arrays whose bound fits are written on the stack, then copied once. +constexpr size_t stack_buffer_size = 1024; + +template +simdjson_inline char *write_element(char *p, T v) noexcept { + if constexpr (std::is_floating_point_v) { + return simdjson::westmere::builder::internal::write_double(p, double(v)); + } else if constexpr (std::is_unsigned_v) { + return simdjson::internal::write_uint(p, static_cast(v)); + } else { + using U = std::make_unsigned_t; + const bool negative = v < 0; + U pv = negative ? U(0) - static_cast(v) : static_cast(v); + *p = '-'; + p += negative; + return simdjson::internal::write_uint(p, static_cast(pv)); + } +} + +template +simdjson_inline char *write_array(char *p, const T *data, size_t n) noexcept { + *p++ = '['; + if (n) { + p = write_element(p, data[0]); + for (size_t i = 1; i < n; i++) { + *p++ = ','; + p = write_element(p, data[i]); + } + } + *p++ = ']'; + return p; +} + +// Not simdjson_inline: MSVC cannot force-inline a function with a try block (C4714). +inline bool assign_bytes(std::string &s, const char *data, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + s.assign(data, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + // Without exceptions, a failed allocation terminates the program. + s.assign(data, n); +#endif + return true; +} + +inline bool resize_for_direct_write(std::string &s, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + simdjson::westmere::builder::internal::resize_uninitialized(s, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + simdjson::westmere::builder::internal::resize_uninitialized(s, n); +#endif + return true; +} + +// A result that fills at most half of the allocation is copied out, as in +// string_builder::move_to. On failure s keeps the larger buffer. +simdjson_never_inline void shrink_to_size(std::string &s) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + std::string(s).swap(s); + } catch (...) { // std::bad_alloc + } +#else + std::string(s).swap(s); +#endif +} + +template +simdjson_warn_unused error_code to_json_array(const T *data, size_t n, std::string &s) noexcept { + constexpr size_t per = max_element_size(); + if (simdjson_unlikely(n > (size_t(-1) - 2 - write_slack) / per)) { + return MEMALLOC; + } + const size_t bound = n * per + 2 + write_slack; + if (bound <= stack_buffer_size) { + simdjson_indeterminate char buffer[stack_buffer_size]; + char *end = write_array(buffer, data, n); + return assign_bytes(s, buffer, size_t(end - buffer)) ? SUCCESS : MEMALLOC; + } + const size_t old_capacity = s.capacity(); + if (!resize_for_direct_write(s, bound)) { + return MEMALLOC; + } + char *begin = &s[0]; + const size_t used = size_t(write_array(begin, data, n) - begin); + s.resize(used); + // A string that could already hold the result is being reused: keep its + // buffer so the next call does not allocate again. + if (old_capacity < used && used <= s.capacity() / 2) { + shrink_to_size(s); + } + return SUCCESS; +} +} // namespace builder_to_json_detail +#endif // SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + +template +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity) { +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + if constexpr (builder_to_json_detail::contiguous_int_array || + builder_to_json_detail::contiguous_float_array) { + (void)initial_capacity; + return builder_to_json_detail::to_json_array(std::ranges::data(z), size_t(std::ranges::size(z)), s); + } else +#endif + { + simdjson::westmere::builder::string_builder b(initial_capacity); + simdjson::westmere::builder::internal::append_value(b, z); + return b.move_to(s); + } +} + +template +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity) { + std::string s; + auto e = to_json(z, s, initial_capacity); + if (e) { return e; } + return s; +} + +} // namespace simdjson +#endif // !SIMDJSON_STATIC_REFLECTION + #endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H /* end file simdjson/generic/builder/json_string_builder-inl.h for westmere */ @@ -62223,6 +66087,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lsx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lsx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -62232,14 +66097,11 @@ namespace lsx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -62464,6 +66326,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -62735,6 +66605,36 @@ namespace builder { using simdjson::internal::escape_best::write_string_escaped; +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +/** + * A contiguous, sized range of integers that string_builder serializes as a + * JSON array of numbers in one pass. Booleans and character types are excluded, + * and so are integers wider than 64 bits. In C++26, std::optional is a + * contiguous range: it is excluded so that the optional overload is chosen. + */ +template +concept integer_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !concepts::optional_type && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; + +namespace internal { +// Elements must be class types (std::string, std::string_view, ...): a +// range of const char * would pay strlen twice. +template +concept contiguous_string_range = + std::ranges::contiguous_range && !concepts::optional_type && + !std::is_convertible_v && + std::is_class_v> && + std::is_convertible_v, std::string_view>; +} // namespace internal +#endif + /** * A builder for JSON strings representing documents. This is a low-level * builder that is not meant to be used directly by end-users. Though it @@ -62888,9 +66788,20 @@ class string_builder { simdjson_inline void append(const T &value); #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + // Contiguous arrays of integers, written without a capacity check per element. + template + requires(!require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; + // Contiguous arrays of strings: one capacity check, then quoted escaped + // elements. Same rationale as the integer-array writer. + template + requires (internal::contiguous_string_range && !require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; // Support for range-based appending (std::ranges::view, etc.) template -requires (!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void append(const R &range) noexcept; #endif /** @@ -63032,6 +66943,14 @@ requires (!std::is_convertible::value && !concepts::optiona simdjson_inline void append_static_string() noexcept; #endif +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + /** + * Append an array of integers too long to reserve its worst case at once. + */ + template + void append_long_integer_array(const int_type *data, size_t n) noexcept; +#endif + /** * Grow the buffer to at least desired_capacity bytes. * If the allocation fails, is_valid is set to false. We expect @@ -63056,6 +66975,18 @@ requires (!std::is_convertible::value && !concepts::optiona bool is_valid{true}; }; +namespace internal { +// Appends value as a JSON value. A char is a one-character string, as in +// append_key_value(): string_builder::append(char) appends a raw character. +template +simdjson_inline void append_value(string_builder &b, const T &value) { + b.append(value); +} +simdjson_inline void append_value(string_builder &b, char value) { + b.escape_and_append_with_quotes(value); +} +} // namespace internal + } @@ -63064,21 +66995,12 @@ requires (!std::is_convertible::value && !concepts::optiona #if !SIMDJSON_STATIC_REFLECTION // fallback implementation until we have static reflection +// Defined in json_string_builder-inl.h so number arrays can write straight +// into the destination string (one allocation, no builder copy). template -simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::lsx::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::lsx::builder::string_builder b(initial_capacity); - b.append(z); - std::string s; - auto e = b.move_to(s); - if(e) { return e; } - return s; -} +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::lsx::builder::string_builder::DEFAULT_INITIAL_CAPACITY); template -simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::lsx::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::lsx::builder::string_builder b(initial_capacity); - b.append(z); - return b.move_to(s); -} +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::lsx::builder::string_builder::DEFAULT_INITIAL_CAPACITY); #endif #if SIMDJSON_SUPPORTS_CONCEPTS @@ -63120,7 +67042,7 @@ namespace builder { // included at the point this header is parsed; without these forwards, // name lookup falls back to the wrong outer namespace). namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; simdjson_inline char *write_double(char *p, double v) noexcept; } // namespace internal @@ -63335,7 +67257,7 @@ template simdjson_really_inline void atom_fields(W &w, const T &t, bool &first) { // Per-field block: ensure key+value worst case, then write key + value // through the writer's local pos. For arithmetic fields, the integer - // write happens directly via write_uint_jeaiii on w.ptr+w.pos, so pos + // write happens directly via write_uint on w.ptr+w.pos, so pos // never round-trips through memory. template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) { if constexpr (is_serialized_member(dm)) { @@ -63484,7 +67406,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { "Integers wider than 64 bits are not supported"); // Booleans / floats: defer to string_builder (rare path; keeps writer hot // path free of float-formatter machinery). For integers, write directly - // via jeaiii using local pos. + // via write_uint using local pos. if constexpr (std::is_same_v) { if (t) { if (!w.ensure(4)) return; @@ -63503,7 +67425,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { } } else if constexpr (std::is_unsigned_v) { if (!w.ensure(20)) return; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(t)); w.pos = static_cast(end - w.ptr); } else { @@ -63514,7 +67436,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { U pv = negative ? U(0) - static_cast(t) : static_cast(t); w.ptr[w.pos] = '-'; w.pos += negative; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(pv)); w.pos = static_cast(end - w.ptr); } @@ -64142,7 +68064,7 @@ simdjson_warn_unused simdjson_result extract_fractured_json( /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #define SIMDJSON_GENERIC_STRING_BUILDER_INL_H */ /* amalgamation skipped (editor-only): #include "simdjson/generic/builder/json_string_builder.h" */ -/* amalgamation skipped (editor-only): #include "simdjson/internal/jeaiii.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/write_uint.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/json_escape.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ @@ -64281,7 +68203,7 @@ simdjson_inline void string_builder::clear() noexcept { namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; // Writes v at p, which must have to_chars_buffer_size bytes available, and // returns the end of what was written. @@ -64298,6 +68220,12 @@ simdjson_inline char *write_double(char *p, double v) noexcept { std::memcpy(p, "Infinity", 8); return p + 8; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(p, "null", 4); + return p + 4; + } #endif return simdjson::internal::to_chars(p, nullptr, v); } @@ -64333,7 +68261,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { constexpr size_t max_number_size = 20; if (capacity_check(max_number_size)) { using unsigned_type = typename std::make_unsigned::type; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(static_cast(v))); position = end - buffer_data(); @@ -64352,7 +68280,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { // Branchless: always write '-', advance only if negative. buffer_data()[position] = '-'; position += negative; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(pv)); position = end - buffer_data(); } @@ -64384,6 +68312,13 @@ simdjson_inline void string_builder::append(number_type v) noexcept { } return; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(buffer_data() + position, "null", 4); + position += 4; + return; + } #endif // We could specialize for float. @@ -64497,7 +68432,7 @@ template requires(!require_custom_serialization) simdjson_inline void string_builder::append(const T &opt) { if (opt) { - append(*opt); + internal::append_value(*this, *opt); } else { append_null(); } @@ -64518,9 +68453,213 @@ simdjson_inline void string_builder::append(const T &value) { #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace internal { +// An element of an integer array takes at most its digits, a sign and a comma. +// write_uint writes past the last digit only below 10^4, and then at most +// four bytes in all, which still fits the bound. +template +constexpr size_t max_integer_element_size = + size_t(std::numeric_limits::digits10) + 2 + + (std::is_signed_v ? 1 : 0); + +// Longer arrays reserve their worst case one block at a time, so that an +// array of short numbers does not reserve many times what it writes. +template +constexpr size_t integer_block_size = + (size_t(1) << 20) / max_integer_element_size; + +template +simdjson_inline char *write_integer(char *p, int_type v) noexcept { + if constexpr (std::is_unsigned_v) { + return write_uint(p, static_cast(v)); + } else { + using unsigned_type = std::make_unsigned_t; + const bool negative = v < 0; + unsigned_type pv = negative ? unsigned_type(0) - static_cast(v) + : static_cast(v); + *p = '-'; + p += negative; + return write_uint(p, static_cast(pv)); + } +} +} // namespace internal + +template + requires(!require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + using int_type = std::ranges::range_value_t; + const int_type *data = std::ranges::data(range); + const size_t n = size_t(std::ranges::size(range)); + if (simdjson_unlikely(n > internal::integer_block_size)) { + append_long_integer_array(data, n); + return; + } + if (!capacity_check(2 + n * internal::max_integer_element_size)) { + return; + } + char *p = buffer_data() + position; + *p++ = '['; + for (size_t i = 0; i < n; i++) { + if (i) { + *p++ = ','; + } + p = internal::write_integer(p, data[i]); + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + +template +simdjson_never_inline void +string_builder::append_long_integer_array(const int_type *data, size_t n) noexcept { + constexpr size_t element_size = internal::max_integer_element_size; + constexpr size_t block_size = internal::integer_block_size; + if (!capacity_check(1)) { + return; + } + const size_t start = position; + buffer_data()[position++] = '['; + size_t i = 0; + while (i < n) { + const size_t count = (n - i < block_size) ? n - i : block_size; + size_t upcoming = count * element_size; + if (i == block_size) { + // Reserve for the remaining elements at the average size seen so far, + // so that the buffer is reallocated about once instead of doubling + // through many sizes. + size_t average = (position - start) / i + 1; + average = average < element_size ? average : element_size; + if (n - i <= (std::numeric_limits::max)() / average) { + const size_t estimate = (n - i) * average; + upcoming = estimate > upcoming ? estimate : upcoming; + } + } + if (!capacity_check(upcoming)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + for (const size_t stop = i + count; i < stop; i++) { + p = internal::write_integer(p, data[i]); + *p++ = ','; + } + position = size_t(p - buffer_data()); + } + // The closing bracket replaces the comma after the last element. + buffer_data()[position - 1] = ']'; +} + +namespace internal { +// Cold path of the string-array writer: the element may not fit its +// worst-case escaped size in the remaining capacity. Writes the element and +// returns the new write pointer, or nullptr if the buffer could not grow. +simdjson_never_inline char *append_quoted_element_slow(string_builder &b, + std::string_view sv, + bool first) noexcept { + auto reserve = [&b](size_t n) { + const size_t pos = b.unsafe_position(); + const size_t cap = b.unsafe_capacity(); + if (n <= cap - pos) { + return true; + } + if (pos + n < pos) { + return false; + } + return b.unsafe_grow((std::max)(cap * 2, pos + n)); + }; + if (sv.size() > 512) { + if (!reserve(6 * sv.size() + 4)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + if (!first) { + *p++ = ','; + } + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + return p; + } + // Escape into a stack buffer first so that we grow by the exact size. + simdjson_indeterminate char tmp[3 + 6 * 512]; + char *tp = tmp; + if (!first) { + *tp++ = ','; + } + *tp++ = '"'; + tp += write_string_escaped(sv, tp); + *tp++ = '"'; + const size_t n = size_t(tp - tmp); + // One more byte for the closing bracket. + if (!reserve(n + 1)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + std::memcpy(p, tmp, n); + return p + n; +} +} // namespace internal + +template + requires (internal::contiguous_string_range && !require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + // Reserve the unescaped size (brackets, commas, quotes, bytes) plus 1/16 + // for escapes. A 6x worst-case reservation made a fresh builder allocate + // several times the output; an exact one made the first escape double + // the buffer. + size_t bytes = 2; + for (const auto &item : range) { + const std::string_view sv = item; + if (sv.size() > ((std::numeric_limits::max)() - 4) / 6 || + sv.size() > (std::numeric_limits::max)() - bytes - 3) { + set_valid(false); + return; + } + bytes += 3 + sv.size(); + } + const size_t slack = bytes / 16; + if (bytes > (std::numeric_limits::max)() - slack) { + set_valid(false); + return; + } + if (!capacity_check(bytes + slack)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + *p++ = '['; + bool first = true; + for (const auto &item : range) { + const std::string_view sv = item; + const size_t off = size_t(p - buffer_data()); + // Comma, two quotes, up to 6 bytes per input byte, closing bracket. + if (simdjson_unlikely(6 * sv.size() + 4 > capacity - off)) { + position = off; + p = internal::append_quoted_element_slow(*this, sv, first); + if (p == nullptr) { + set_valid(false); + return; + } + first = false; + continue; + } + if (!first) { + *p++ = ','; + } + first = false; + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + // Support for range-based appending (std::ranges::view, etc.) template - requires(!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void string_builder::append(const R &range) noexcept { auto it = std::ranges::begin(range); auto end = std::ranges::end(range); @@ -64549,13 +68688,13 @@ simdjson_inline void string_builder::append(const R &range) noexcept { } // Append first item without leading comma - append(*it); + internal::append_value(*this, *it); ++it; // Append remaining items with preceding commas for (; it != end; ++it) { append_comma(); - append(*it); + internal::append_value(*this, *it); } end_array(); } @@ -64755,6 +68894,175 @@ string_builder::append_key_value() noexcept { } // namespace lsx } // namespace simdjson + +#if !SIMDJSON_STATIC_REFLECTION +namespace simdjson { + +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace builder_to_json_detail { +// Concepts, not constexpr bools: a conjunction of concepts stops at the +// first unsatisfied one, so range_value_t is never formed for a non-range. +template +concept contiguous_number_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !require_custom_serialization; +template +concept contiguous_int_array = + contiguous_number_array && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; +template +concept contiguous_float_array = + contiguous_number_array && + std::is_floating_point_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t); + +// Most bytes one element writes, the comma before it included. A double +// takes at most 24 characters (-d.dddddddddddddddde-308). +template +constexpr size_t max_element_size() { + if constexpr (std::is_floating_point_v) { + return 24 + 1; + } else { + return size_t(std::numeric_limits::digits10) + 1 + std::is_signed_v + 1; + } +} +// The number writers may write scratch bytes past the end of the number. +constexpr size_t write_slack = simdjson::internal::to_chars_buffer_size; +// Arrays whose bound fits are written on the stack, then copied once. +constexpr size_t stack_buffer_size = 1024; + +template +simdjson_inline char *write_element(char *p, T v) noexcept { + if constexpr (std::is_floating_point_v) { + return simdjson::lsx::builder::internal::write_double(p, double(v)); + } else if constexpr (std::is_unsigned_v) { + return simdjson::internal::write_uint(p, static_cast(v)); + } else { + using U = std::make_unsigned_t; + const bool negative = v < 0; + U pv = negative ? U(0) - static_cast(v) : static_cast(v); + *p = '-'; + p += negative; + return simdjson::internal::write_uint(p, static_cast(pv)); + } +} + +template +simdjson_inline char *write_array(char *p, const T *data, size_t n) noexcept { + *p++ = '['; + if (n) { + p = write_element(p, data[0]); + for (size_t i = 1; i < n; i++) { + *p++ = ','; + p = write_element(p, data[i]); + } + } + *p++ = ']'; + return p; +} + +// Not simdjson_inline: MSVC cannot force-inline a function with a try block (C4714). +inline bool assign_bytes(std::string &s, const char *data, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + s.assign(data, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + // Without exceptions, a failed allocation terminates the program. + s.assign(data, n); +#endif + return true; +} + +inline bool resize_for_direct_write(std::string &s, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + simdjson::lsx::builder::internal::resize_uninitialized(s, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + simdjson::lsx::builder::internal::resize_uninitialized(s, n); +#endif + return true; +} + +// A result that fills at most half of the allocation is copied out, as in +// string_builder::move_to. On failure s keeps the larger buffer. +simdjson_never_inline void shrink_to_size(std::string &s) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + std::string(s).swap(s); + } catch (...) { // std::bad_alloc + } +#else + std::string(s).swap(s); +#endif +} + +template +simdjson_warn_unused error_code to_json_array(const T *data, size_t n, std::string &s) noexcept { + constexpr size_t per = max_element_size(); + if (simdjson_unlikely(n > (size_t(-1) - 2 - write_slack) / per)) { + return MEMALLOC; + } + const size_t bound = n * per + 2 + write_slack; + if (bound <= stack_buffer_size) { + simdjson_indeterminate char buffer[stack_buffer_size]; + char *end = write_array(buffer, data, n); + return assign_bytes(s, buffer, size_t(end - buffer)) ? SUCCESS : MEMALLOC; + } + const size_t old_capacity = s.capacity(); + if (!resize_for_direct_write(s, bound)) { + return MEMALLOC; + } + char *begin = &s[0]; + const size_t used = size_t(write_array(begin, data, n) - begin); + s.resize(used); + // A string that could already hold the result is being reused: keep its + // buffer so the next call does not allocate again. + if (old_capacity < used && used <= s.capacity() / 2) { + shrink_to_size(s); + } + return SUCCESS; +} +} // namespace builder_to_json_detail +#endif // SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + +template +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity) { +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + if constexpr (builder_to_json_detail::contiguous_int_array || + builder_to_json_detail::contiguous_float_array) { + (void)initial_capacity; + return builder_to_json_detail::to_json_array(std::ranges::data(z), size_t(std::ranges::size(z)), s); + } else +#endif + { + simdjson::lsx::builder::string_builder b(initial_capacity); + simdjson::lsx::builder::internal::append_value(b, z); + return b.move_to(s); + } +} + +template +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity) { + std::string s; + auto e = to_json(z, s, initial_capacity); + if (e) { return e; } + return s; +} + +} // namespace simdjson +#endif // !SIMDJSON_STATIC_REFLECTION + #endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H /* end file simdjson/generic/builder/json_string_builder-inl.h for lsx */ @@ -64937,6 +69245,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lasx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lasx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -64946,14 +69255,11 @@ namespace lasx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -65205,6 +69511,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[32]; + std::memset(block, fill, 32); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -65464,6 +69778,36 @@ namespace builder { using simdjson::internal::escape_best::write_string_escaped; +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +/** + * A contiguous, sized range of integers that string_builder serializes as a + * JSON array of numbers in one pass. Booleans and character types are excluded, + * and so are integers wider than 64 bits. In C++26, std::optional is a + * contiguous range: it is excluded so that the optional overload is chosen. + */ +template +concept integer_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !concepts::optional_type && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; + +namespace internal { +// Elements must be class types (std::string, std::string_view, ...): a +// range of const char * would pay strlen twice. +template +concept contiguous_string_range = + std::ranges::contiguous_range && !concepts::optional_type && + !std::is_convertible_v && + std::is_class_v> && + std::is_convertible_v, std::string_view>; +} // namespace internal +#endif + /** * A builder for JSON strings representing documents. This is a low-level * builder that is not meant to be used directly by end-users. Though it @@ -65617,9 +69961,20 @@ class string_builder { simdjson_inline void append(const T &value); #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + // Contiguous arrays of integers, written without a capacity check per element. + template + requires(!require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; + // Contiguous arrays of strings: one capacity check, then quoted escaped + // elements. Same rationale as the integer-array writer. + template + requires (internal::contiguous_string_range && !require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; // Support for range-based appending (std::ranges::view, etc.) template -requires (!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void append(const R &range) noexcept; #endif /** @@ -65761,6 +70116,14 @@ requires (!std::is_convertible::value && !concepts::optiona simdjson_inline void append_static_string() noexcept; #endif +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + /** + * Append an array of integers too long to reserve its worst case at once. + */ + template + void append_long_integer_array(const int_type *data, size_t n) noexcept; +#endif + /** * Grow the buffer to at least desired_capacity bytes. * If the allocation fails, is_valid is set to false. We expect @@ -65785,6 +70148,18 @@ requires (!std::is_convertible::value && !concepts::optiona bool is_valid{true}; }; +namespace internal { +// Appends value as a JSON value. A char is a one-character string, as in +// append_key_value(): string_builder::append(char) appends a raw character. +template +simdjson_inline void append_value(string_builder &b, const T &value) { + b.append(value); +} +simdjson_inline void append_value(string_builder &b, char value) { + b.escape_and_append_with_quotes(value); +} +} // namespace internal + } @@ -65793,21 +70168,12 @@ requires (!std::is_convertible::value && !concepts::optiona #if !SIMDJSON_STATIC_REFLECTION // fallback implementation until we have static reflection +// Defined in json_string_builder-inl.h so number arrays can write straight +// into the destination string (one allocation, no builder copy). template -simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::lasx::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::lasx::builder::string_builder b(initial_capacity); - b.append(z); - std::string s; - auto e = b.move_to(s); - if(e) { return e; } - return s; -} +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::lasx::builder::string_builder::DEFAULT_INITIAL_CAPACITY); template -simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::lasx::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::lasx::builder::string_builder b(initial_capacity); - b.append(z); - return b.move_to(s); -} +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::lasx::builder::string_builder::DEFAULT_INITIAL_CAPACITY); #endif #if SIMDJSON_SUPPORTS_CONCEPTS @@ -65849,7 +70215,7 @@ namespace builder { // included at the point this header is parsed; without these forwards, // name lookup falls back to the wrong outer namespace). namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; simdjson_inline char *write_double(char *p, double v) noexcept; } // namespace internal @@ -66064,7 +70430,7 @@ template simdjson_really_inline void atom_fields(W &w, const T &t, bool &first) { // Per-field block: ensure key+value worst case, then write key + value // through the writer's local pos. For arithmetic fields, the integer - // write happens directly via write_uint_jeaiii on w.ptr+w.pos, so pos + // write happens directly via write_uint on w.ptr+w.pos, so pos // never round-trips through memory. template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) { if constexpr (is_serialized_member(dm)) { @@ -66213,7 +70579,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { "Integers wider than 64 bits are not supported"); // Booleans / floats: defer to string_builder (rare path; keeps writer hot // path free of float-formatter machinery). For integers, write directly - // via jeaiii using local pos. + // via write_uint using local pos. if constexpr (std::is_same_v) { if (t) { if (!w.ensure(4)) return; @@ -66232,7 +70598,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { } } else if constexpr (std::is_unsigned_v) { if (!w.ensure(20)) return; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(t)); w.pos = static_cast(end - w.ptr); } else { @@ -66243,7 +70609,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { U pv = negative ? U(0) - static_cast(t) : static_cast(t); w.ptr[w.pos] = '-'; w.pos += negative; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(pv)); w.pos = static_cast(end - w.ptr); } @@ -66871,7 +71237,7 @@ simdjson_warn_unused simdjson_result extract_fractured_json( /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #define SIMDJSON_GENERIC_STRING_BUILDER_INL_H */ /* amalgamation skipped (editor-only): #include "simdjson/generic/builder/json_string_builder.h" */ -/* amalgamation skipped (editor-only): #include "simdjson/internal/jeaiii.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/write_uint.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/json_escape.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ @@ -67010,7 +71376,7 @@ simdjson_inline void string_builder::clear() noexcept { namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; // Writes v at p, which must have to_chars_buffer_size bytes available, and // returns the end of what was written. @@ -67027,6 +71393,12 @@ simdjson_inline char *write_double(char *p, double v) noexcept { std::memcpy(p, "Infinity", 8); return p + 8; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(p, "null", 4); + return p + 4; + } #endif return simdjson::internal::to_chars(p, nullptr, v); } @@ -67062,7 +71434,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { constexpr size_t max_number_size = 20; if (capacity_check(max_number_size)) { using unsigned_type = typename std::make_unsigned::type; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(static_cast(v))); position = end - buffer_data(); @@ -67081,7 +71453,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { // Branchless: always write '-', advance only if negative. buffer_data()[position] = '-'; position += negative; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(pv)); position = end - buffer_data(); } @@ -67113,6 +71485,13 @@ simdjson_inline void string_builder::append(number_type v) noexcept { } return; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(buffer_data() + position, "null", 4); + position += 4; + return; + } #endif // We could specialize for float. @@ -67226,7 +71605,7 @@ template requires(!require_custom_serialization) simdjson_inline void string_builder::append(const T &opt) { if (opt) { - append(*opt); + internal::append_value(*this, *opt); } else { append_null(); } @@ -67247,9 +71626,213 @@ simdjson_inline void string_builder::append(const T &value) { #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace internal { +// An element of an integer array takes at most its digits, a sign and a comma. +// write_uint writes past the last digit only below 10^4, and then at most +// four bytes in all, which still fits the bound. +template +constexpr size_t max_integer_element_size = + size_t(std::numeric_limits::digits10) + 2 + + (std::is_signed_v ? 1 : 0); + +// Longer arrays reserve their worst case one block at a time, so that an +// array of short numbers does not reserve many times what it writes. +template +constexpr size_t integer_block_size = + (size_t(1) << 20) / max_integer_element_size; + +template +simdjson_inline char *write_integer(char *p, int_type v) noexcept { + if constexpr (std::is_unsigned_v) { + return write_uint(p, static_cast(v)); + } else { + using unsigned_type = std::make_unsigned_t; + const bool negative = v < 0; + unsigned_type pv = negative ? unsigned_type(0) - static_cast(v) + : static_cast(v); + *p = '-'; + p += negative; + return write_uint(p, static_cast(pv)); + } +} +} // namespace internal + +template + requires(!require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + using int_type = std::ranges::range_value_t; + const int_type *data = std::ranges::data(range); + const size_t n = size_t(std::ranges::size(range)); + if (simdjson_unlikely(n > internal::integer_block_size)) { + append_long_integer_array(data, n); + return; + } + if (!capacity_check(2 + n * internal::max_integer_element_size)) { + return; + } + char *p = buffer_data() + position; + *p++ = '['; + for (size_t i = 0; i < n; i++) { + if (i) { + *p++ = ','; + } + p = internal::write_integer(p, data[i]); + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + +template +simdjson_never_inline void +string_builder::append_long_integer_array(const int_type *data, size_t n) noexcept { + constexpr size_t element_size = internal::max_integer_element_size; + constexpr size_t block_size = internal::integer_block_size; + if (!capacity_check(1)) { + return; + } + const size_t start = position; + buffer_data()[position++] = '['; + size_t i = 0; + while (i < n) { + const size_t count = (n - i < block_size) ? n - i : block_size; + size_t upcoming = count * element_size; + if (i == block_size) { + // Reserve for the remaining elements at the average size seen so far, + // so that the buffer is reallocated about once instead of doubling + // through many sizes. + size_t average = (position - start) / i + 1; + average = average < element_size ? average : element_size; + if (n - i <= (std::numeric_limits::max)() / average) { + const size_t estimate = (n - i) * average; + upcoming = estimate > upcoming ? estimate : upcoming; + } + } + if (!capacity_check(upcoming)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + for (const size_t stop = i + count; i < stop; i++) { + p = internal::write_integer(p, data[i]); + *p++ = ','; + } + position = size_t(p - buffer_data()); + } + // The closing bracket replaces the comma after the last element. + buffer_data()[position - 1] = ']'; +} + +namespace internal { +// Cold path of the string-array writer: the element may not fit its +// worst-case escaped size in the remaining capacity. Writes the element and +// returns the new write pointer, or nullptr if the buffer could not grow. +simdjson_never_inline char *append_quoted_element_slow(string_builder &b, + std::string_view sv, + bool first) noexcept { + auto reserve = [&b](size_t n) { + const size_t pos = b.unsafe_position(); + const size_t cap = b.unsafe_capacity(); + if (n <= cap - pos) { + return true; + } + if (pos + n < pos) { + return false; + } + return b.unsafe_grow((std::max)(cap * 2, pos + n)); + }; + if (sv.size() > 512) { + if (!reserve(6 * sv.size() + 4)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + if (!first) { + *p++ = ','; + } + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + return p; + } + // Escape into a stack buffer first so that we grow by the exact size. + simdjson_indeterminate char tmp[3 + 6 * 512]; + char *tp = tmp; + if (!first) { + *tp++ = ','; + } + *tp++ = '"'; + tp += write_string_escaped(sv, tp); + *tp++ = '"'; + const size_t n = size_t(tp - tmp); + // One more byte for the closing bracket. + if (!reserve(n + 1)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + std::memcpy(p, tmp, n); + return p + n; +} +} // namespace internal + +template + requires (internal::contiguous_string_range && !require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + // Reserve the unescaped size (brackets, commas, quotes, bytes) plus 1/16 + // for escapes. A 6x worst-case reservation made a fresh builder allocate + // several times the output; an exact one made the first escape double + // the buffer. + size_t bytes = 2; + for (const auto &item : range) { + const std::string_view sv = item; + if (sv.size() > ((std::numeric_limits::max)() - 4) / 6 || + sv.size() > (std::numeric_limits::max)() - bytes - 3) { + set_valid(false); + return; + } + bytes += 3 + sv.size(); + } + const size_t slack = bytes / 16; + if (bytes > (std::numeric_limits::max)() - slack) { + set_valid(false); + return; + } + if (!capacity_check(bytes + slack)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + *p++ = '['; + bool first = true; + for (const auto &item : range) { + const std::string_view sv = item; + const size_t off = size_t(p - buffer_data()); + // Comma, two quotes, up to 6 bytes per input byte, closing bracket. + if (simdjson_unlikely(6 * sv.size() + 4 > capacity - off)) { + position = off; + p = internal::append_quoted_element_slow(*this, sv, first); + if (p == nullptr) { + set_valid(false); + return; + } + first = false; + continue; + } + if (!first) { + *p++ = ','; + } + first = false; + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + // Support for range-based appending (std::ranges::view, etc.) template - requires(!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void string_builder::append(const R &range) noexcept { auto it = std::ranges::begin(range); auto end = std::ranges::end(range); @@ -67278,13 +71861,13 @@ simdjson_inline void string_builder::append(const R &range) noexcept { } // Append first item without leading comma - append(*it); + internal::append_value(*this, *it); ++it; // Append remaining items with preceding commas for (; it != end; ++it) { append_comma(); - append(*it); + internal::append_value(*this, *it); } end_array(); } @@ -67484,6 +72067,175 @@ string_builder::append_key_value() noexcept { } // namespace lasx } // namespace simdjson + +#if !SIMDJSON_STATIC_REFLECTION +namespace simdjson { + +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace builder_to_json_detail { +// Concepts, not constexpr bools: a conjunction of concepts stops at the +// first unsatisfied one, so range_value_t is never formed for a non-range. +template +concept contiguous_number_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !require_custom_serialization; +template +concept contiguous_int_array = + contiguous_number_array && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; +template +concept contiguous_float_array = + contiguous_number_array && + std::is_floating_point_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t); + +// Most bytes one element writes, the comma before it included. A double +// takes at most 24 characters (-d.dddddddddddddddde-308). +template +constexpr size_t max_element_size() { + if constexpr (std::is_floating_point_v) { + return 24 + 1; + } else { + return size_t(std::numeric_limits::digits10) + 1 + std::is_signed_v + 1; + } +} +// The number writers may write scratch bytes past the end of the number. +constexpr size_t write_slack = simdjson::internal::to_chars_buffer_size; +// Arrays whose bound fits are written on the stack, then copied once. +constexpr size_t stack_buffer_size = 1024; + +template +simdjson_inline char *write_element(char *p, T v) noexcept { + if constexpr (std::is_floating_point_v) { + return simdjson::lasx::builder::internal::write_double(p, double(v)); + } else if constexpr (std::is_unsigned_v) { + return simdjson::internal::write_uint(p, static_cast(v)); + } else { + using U = std::make_unsigned_t; + const bool negative = v < 0; + U pv = negative ? U(0) - static_cast(v) : static_cast(v); + *p = '-'; + p += negative; + return simdjson::internal::write_uint(p, static_cast(pv)); + } +} + +template +simdjson_inline char *write_array(char *p, const T *data, size_t n) noexcept { + *p++ = '['; + if (n) { + p = write_element(p, data[0]); + for (size_t i = 1; i < n; i++) { + *p++ = ','; + p = write_element(p, data[i]); + } + } + *p++ = ']'; + return p; +} + +// Not simdjson_inline: MSVC cannot force-inline a function with a try block (C4714). +inline bool assign_bytes(std::string &s, const char *data, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + s.assign(data, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + // Without exceptions, a failed allocation terminates the program. + s.assign(data, n); +#endif + return true; +} + +inline bool resize_for_direct_write(std::string &s, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + simdjson::lasx::builder::internal::resize_uninitialized(s, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + simdjson::lasx::builder::internal::resize_uninitialized(s, n); +#endif + return true; +} + +// A result that fills at most half of the allocation is copied out, as in +// string_builder::move_to. On failure s keeps the larger buffer. +simdjson_never_inline void shrink_to_size(std::string &s) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + std::string(s).swap(s); + } catch (...) { // std::bad_alloc + } +#else + std::string(s).swap(s); +#endif +} + +template +simdjson_warn_unused error_code to_json_array(const T *data, size_t n, std::string &s) noexcept { + constexpr size_t per = max_element_size(); + if (simdjson_unlikely(n > (size_t(-1) - 2 - write_slack) / per)) { + return MEMALLOC; + } + const size_t bound = n * per + 2 + write_slack; + if (bound <= stack_buffer_size) { + simdjson_indeterminate char buffer[stack_buffer_size]; + char *end = write_array(buffer, data, n); + return assign_bytes(s, buffer, size_t(end - buffer)) ? SUCCESS : MEMALLOC; + } + const size_t old_capacity = s.capacity(); + if (!resize_for_direct_write(s, bound)) { + return MEMALLOC; + } + char *begin = &s[0]; + const size_t used = size_t(write_array(begin, data, n) - begin); + s.resize(used); + // A string that could already hold the result is being reused: keep its + // buffer so the next call does not allocate again. + if (old_capacity < used && used <= s.capacity() / 2) { + shrink_to_size(s); + } + return SUCCESS; +} +} // namespace builder_to_json_detail +#endif // SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + +template +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity) { +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + if constexpr (builder_to_json_detail::contiguous_int_array || + builder_to_json_detail::contiguous_float_array) { + (void)initial_capacity; + return builder_to_json_detail::to_json_array(std::ranges::data(z), size_t(std::ranges::size(z)), s); + } else +#endif + { + simdjson::lasx::builder::string_builder b(initial_capacity); + simdjson::lasx::builder::internal::append_value(b, z); + return b.move_to(s); + } +} + +template +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity) { + std::string s; + auto e = to_json(z, s, initial_capacity); + if (e) { return e; } + return s; +} + +} // namespace simdjson +#endif // !SIMDJSON_STATIC_REFLECTION + #endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H /* end file simdjson/generic/builder/json_string_builder-inl.h for lasx */ @@ -67763,6 +72515,14 @@ namespace simd { simdjson_inline simd8() : simd8(zero()) {} simdjson_inline simd8(const uint8_t values[VL8]) : simd8(load(values)) {} simdjson_inline simd8(uint8_t _value) : simd8(splat(_value)) {} + // The n < VL8 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[VL8]; + std::memset(block, fill, VL8); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8(simd8 mask) : value(__riscv_vmerge_vxm_u8m1(zero(), -1, (vbool_t)mask, VL8)) {} simdjson_inline operator const vuint8_t&() const { return this->value; } @@ -68099,6 +72859,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/rvv-vls/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -68114,7 +72875,6 @@ namespace simdjson { namespace rvv_vls { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; @@ -68123,9 +72883,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { #else val = __riscv_vmv_x(__riscv_vreinterpret_u64m1(__riscv_vlmul_ext_u8m1(__riscv_vle8_v_u8mf2((uint8_t*)chars, 8)))); #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -68206,6 +72964,36 @@ namespace builder { using simdjson::internal::escape_best::write_string_escaped; +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +/** + * A contiguous, sized range of integers that string_builder serializes as a + * JSON array of numbers in one pass. Booleans and character types are excluded, + * and so are integers wider than 64 bits. In C++26, std::optional is a + * contiguous range: it is excluded so that the optional overload is chosen. + */ +template +concept integer_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !concepts::optional_type && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; + +namespace internal { +// Elements must be class types (std::string, std::string_view, ...): a +// range of const char * would pay strlen twice. +template +concept contiguous_string_range = + std::ranges::contiguous_range && !concepts::optional_type && + !std::is_convertible_v && + std::is_class_v> && + std::is_convertible_v, std::string_view>; +} // namespace internal +#endif + /** * A builder for JSON strings representing documents. This is a low-level * builder that is not meant to be used directly by end-users. Though it @@ -68359,9 +73147,20 @@ class string_builder { simdjson_inline void append(const T &value); #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + // Contiguous arrays of integers, written without a capacity check per element. + template + requires(!require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; + // Contiguous arrays of strings: one capacity check, then quoted escaped + // elements. Same rationale as the integer-array writer. + template + requires (internal::contiguous_string_range && !require_custom_serialization) + simdjson_inline void append(const R &range) noexcept; // Support for range-based appending (std::ranges::view, etc.) template -requires (!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void append(const R &range) noexcept; #endif /** @@ -68503,6 +73302,14 @@ requires (!std::is_convertible::value && !concepts::optiona simdjson_inline void append_static_string() noexcept; #endif +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + /** + * Append an array of integers too long to reserve its worst case at once. + */ + template + void append_long_integer_array(const int_type *data, size_t n) noexcept; +#endif + /** * Grow the buffer to at least desired_capacity bytes. * If the allocation fails, is_valid is set to false. We expect @@ -68527,6 +73334,18 @@ requires (!std::is_convertible::value && !concepts::optiona bool is_valid{true}; }; +namespace internal { +// Appends value as a JSON value. A char is a one-character string, as in +// append_key_value(): string_builder::append(char) appends a raw character. +template +simdjson_inline void append_value(string_builder &b, const T &value) { + b.append(value); +} +simdjson_inline void append_value(string_builder &b, char value) { + b.escape_and_append_with_quotes(value); +} +} // namespace internal + } @@ -68535,21 +73354,12 @@ requires (!std::is_convertible::value && !concepts::optiona #if !SIMDJSON_STATIC_REFLECTION // fallback implementation until we have static reflection +// Defined in json_string_builder-inl.h so number arrays can write straight +// into the destination string (one allocation, no builder copy). template -simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::rvv_vls::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::rvv_vls::builder::string_builder b(initial_capacity); - b.append(z); - std::string s; - auto e = b.move_to(s); - if(e) { return e; } - return s; -} +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity = simdjson::rvv_vls::builder::string_builder::DEFAULT_INITIAL_CAPACITY); template -simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::rvv_vls::builder::string_builder::DEFAULT_INITIAL_CAPACITY) { - simdjson::rvv_vls::builder::string_builder b(initial_capacity); - b.append(z); - return b.move_to(s); -} +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity = simdjson::rvv_vls::builder::string_builder::DEFAULT_INITIAL_CAPACITY); #endif #if SIMDJSON_SUPPORTS_CONCEPTS @@ -68591,7 +73401,7 @@ namespace builder { // included at the point this header is parsed; without these forwards, // name lookup falls back to the wrong outer namespace). namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; simdjson_inline char *write_double(char *p, double v) noexcept; } // namespace internal @@ -68806,7 +73616,7 @@ template simdjson_really_inline void atom_fields(W &w, const T &t, bool &first) { // Per-field block: ensure key+value worst case, then write key + value // through the writer's local pos. For arithmetic fields, the integer - // write happens directly via write_uint_jeaiii on w.ptr+w.pos, so pos + // write happens directly via write_uint on w.ptr+w.pos, so pos // never round-trips through memory. template for (constexpr auto dm : std::define_static_array(std::meta::nonstatic_data_members_of(^^T, std::meta::access_context::unchecked()))) { if constexpr (is_serialized_member(dm)) { @@ -68955,7 +73765,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { "Integers wider than 64 bits are not supported"); // Booleans / floats: defer to string_builder (rare path; keeps writer hot // path free of float-formatter machinery). For integers, write directly - // via jeaiii using local pos. + // via write_uint using local pos. if constexpr (std::is_same_v) { if (t) { if (!w.ensure(4)) return; @@ -68974,7 +73784,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { } } else if constexpr (std::is_unsigned_v) { if (!w.ensure(20)) return; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(t)); w.pos = static_cast(end - w.ptr); } else { @@ -68985,7 +73795,7 @@ simdjson_really_inline constexpr void atom(W &w, const number_type t) { U pv = negative ? U(0) - static_cast(t) : static_cast(t); w.ptr[w.pos] = '-'; w.pos += negative; - char *end = internal::write_uint_jeaiii( + char *end = internal::write_uint( w.ptr + w.pos, static_cast(pv)); w.pos = static_cast(end - w.ptr); } @@ -69613,7 +74423,7 @@ simdjson_warn_unused simdjson_result extract_fractured_json( /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #define SIMDJSON_GENERIC_STRING_BUILDER_INL_H */ /* amalgamation skipped (editor-only): #include "simdjson/generic/builder/json_string_builder.h" */ -/* amalgamation skipped (editor-only): #include "simdjson/internal/jeaiii.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/write_uint.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/json_escape.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ @@ -69752,7 +74562,7 @@ simdjson_inline void string_builder::clear() noexcept { namespace internal { -using simdjson::internal::write_uint_jeaiii; +using simdjson::internal::write_uint; // Writes v at p, which must have to_chars_buffer_size bytes available, and // returns the end of what was written. @@ -69769,6 +74579,12 @@ simdjson_inline char *write_double(char *p, double v) noexcept { std::memcpy(p, "Infinity", 8); return p + 8; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(p, "null", 4); + return p + 4; + } #endif return simdjson::internal::to_chars(p, nullptr, v); } @@ -69804,7 +74620,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { constexpr size_t max_number_size = 20; if (capacity_check(max_number_size)) { using unsigned_type = typename std::make_unsigned::type; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(static_cast(v))); position = end - buffer_data(); @@ -69823,7 +74639,7 @@ simdjson_inline void string_builder::append(number_type v) noexcept { // Branchless: always write '-', advance only if negative. buffer_data()[position] = '-'; position += negative; - char* end = internal::write_uint_jeaiii( + char* end = internal::write_uint( buffer_data() + position, static_cast(pv)); position = end - buffer_data(); } @@ -69855,6 +74671,13 @@ simdjson_inline void string_builder::append(number_type v) noexcept { } return; } +#else + // JSON has no NaN or Infinity: write null, as JSON.stringify does. + if (simdjson_unlikely(!std::isfinite(v))) { + std::memcpy(buffer_data() + position, "null", 4); + position += 4; + return; + } #endif // We could specialize for float. @@ -69968,7 +74791,7 @@ template requires(!require_custom_serialization) simdjson_inline void string_builder::append(const T &opt) { if (opt) { - append(*opt); + internal::append_value(*this, *opt); } else { append_null(); } @@ -69989,9 +74812,213 @@ simdjson_inline void string_builder::append(const T &value) { #endif #if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace internal { +// An element of an integer array takes at most its digits, a sign and a comma. +// write_uint writes past the last digit only below 10^4, and then at most +// four bytes in all, which still fits the bound. +template +constexpr size_t max_integer_element_size = + size_t(std::numeric_limits::digits10) + 2 + + (std::is_signed_v ? 1 : 0); + +// Longer arrays reserve their worst case one block at a time, so that an +// array of short numbers does not reserve many times what it writes. +template +constexpr size_t integer_block_size = + (size_t(1) << 20) / max_integer_element_size; + +template +simdjson_inline char *write_integer(char *p, int_type v) noexcept { + if constexpr (std::is_unsigned_v) { + return write_uint(p, static_cast(v)); + } else { + using unsigned_type = std::make_unsigned_t; + const bool negative = v < 0; + unsigned_type pv = negative ? unsigned_type(0) - static_cast(v) + : static_cast(v); + *p = '-'; + p += negative; + return write_uint(p, static_cast(pv)); + } +} +} // namespace internal + +template + requires(!require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + using int_type = std::ranges::range_value_t; + const int_type *data = std::ranges::data(range); + const size_t n = size_t(std::ranges::size(range)); + if (simdjson_unlikely(n > internal::integer_block_size)) { + append_long_integer_array(data, n); + return; + } + if (!capacity_check(2 + n * internal::max_integer_element_size)) { + return; + } + char *p = buffer_data() + position; + *p++ = '['; + for (size_t i = 0; i < n; i++) { + if (i) { + *p++ = ','; + } + p = internal::write_integer(p, data[i]); + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + +template +simdjson_never_inline void +string_builder::append_long_integer_array(const int_type *data, size_t n) noexcept { + constexpr size_t element_size = internal::max_integer_element_size; + constexpr size_t block_size = internal::integer_block_size; + if (!capacity_check(1)) { + return; + } + const size_t start = position; + buffer_data()[position++] = '['; + size_t i = 0; + while (i < n) { + const size_t count = (n - i < block_size) ? n - i : block_size; + size_t upcoming = count * element_size; + if (i == block_size) { + // Reserve for the remaining elements at the average size seen so far, + // so that the buffer is reallocated about once instead of doubling + // through many sizes. + size_t average = (position - start) / i + 1; + average = average < element_size ? average : element_size; + if (n - i <= (std::numeric_limits::max)() / average) { + const size_t estimate = (n - i) * average; + upcoming = estimate > upcoming ? estimate : upcoming; + } + } + if (!capacity_check(upcoming)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + for (const size_t stop = i + count; i < stop; i++) { + p = internal::write_integer(p, data[i]); + *p++ = ','; + } + position = size_t(p - buffer_data()); + } + // The closing bracket replaces the comma after the last element. + buffer_data()[position - 1] = ']'; +} + +namespace internal { +// Cold path of the string-array writer: the element may not fit its +// worst-case escaped size in the remaining capacity. Writes the element and +// returns the new write pointer, or nullptr if the buffer could not grow. +simdjson_never_inline char *append_quoted_element_slow(string_builder &b, + std::string_view sv, + bool first) noexcept { + auto reserve = [&b](size_t n) { + const size_t pos = b.unsafe_position(); + const size_t cap = b.unsafe_capacity(); + if (n <= cap - pos) { + return true; + } + if (pos + n < pos) { + return false; + } + return b.unsafe_grow((std::max)(cap * 2, pos + n)); + }; + if (sv.size() > 512) { + if (!reserve(6 * sv.size() + 4)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + if (!first) { + *p++ = ','; + } + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + return p; + } + // Escape into a stack buffer first so that we grow by the exact size. + simdjson_indeterminate char tmp[3 + 6 * 512]; + char *tp = tmp; + if (!first) { + *tp++ = ','; + } + *tp++ = '"'; + tp += write_string_escaped(sv, tp); + *tp++ = '"'; + const size_t n = size_t(tp - tmp); + // One more byte for the closing bracket. + if (!reserve(n + 1)) { + return nullptr; + } + char *p = b.unsafe_data() + b.unsafe_position(); + std::memcpy(p, tmp, n); + return p + n; +} +} // namespace internal + +template + requires (internal::contiguous_string_range && !require_custom_serialization) +simdjson_inline void string_builder::append(const R &range) noexcept { + // Reserve the unescaped size (brackets, commas, quotes, bytes) plus 1/16 + // for escapes. A 6x worst-case reservation made a fresh builder allocate + // several times the output; an exact one made the first escape double + // the buffer. + size_t bytes = 2; + for (const auto &item : range) { + const std::string_view sv = item; + if (sv.size() > ((std::numeric_limits::max)() - 4) / 6 || + sv.size() > (std::numeric_limits::max)() - bytes - 3) { + set_valid(false); + return; + } + bytes += 3 + sv.size(); + } + const size_t slack = bytes / 16; + if (bytes > (std::numeric_limits::max)() - slack) { + set_valid(false); + return; + } + if (!capacity_check(bytes + slack)) { + set_valid(false); + return; + } + char *p = buffer_data() + position; + *p++ = '['; + bool first = true; + for (const auto &item : range) { + const std::string_view sv = item; + const size_t off = size_t(p - buffer_data()); + // Comma, two quotes, up to 6 bytes per input byte, closing bracket. + if (simdjson_unlikely(6 * sv.size() + 4 > capacity - off)) { + position = off; + p = internal::append_quoted_element_slow(*this, sv, first); + if (p == nullptr) { + set_valid(false); + return; + } + first = false; + continue; + } + if (!first) { + *p++ = ','; + } + first = false; + *p++ = '"'; + p += write_string_escaped(sv, p); + *p++ = '"'; + } + *p++ = ']'; + position = size_t(p - buffer_data()); +} + // Support for range-based appending (std::ranges::view, etc.) template - requires(!std::is_convertible::value && !concepts::optional_type && !require_custom_serialization) + requires(!std::is_convertible::value && !concepts::optional_type && + !require_custom_serialization && !integer_array && + !internal::contiguous_string_range) simdjson_inline void string_builder::append(const R &range) noexcept { auto it = std::ranges::begin(range); auto end = std::ranges::end(range); @@ -70020,13 +75047,13 @@ simdjson_inline void string_builder::append(const R &range) noexcept { } // Append first item without leading comma - append(*it); + internal::append_value(*this, *it); ++it; // Append remaining items with preceding commas for (; it != end; ++it) { append_comma(); - append(*it); + internal::append_value(*this, *it); } end_array(); } @@ -70226,6 +75253,175 @@ string_builder::append_key_value() noexcept { } // namespace rvv_vls } // namespace simdjson + +#if !SIMDJSON_STATIC_REFLECTION +namespace simdjson { + +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS +namespace builder_to_json_detail { +// Concepts, not constexpr bools: a conjunction of concepts stops at the +// first unsatisfied one, so range_value_t is never formed for a non-range. +template +concept contiguous_number_array = + std::ranges::contiguous_range && std::ranges::sized_range && + !require_custom_serialization; +template +concept contiguous_int_array = + contiguous_number_array && + std::is_integral_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t) && + !std::is_same_v, bool> && + !std::is_same_v, char> && + !std::is_same_v, signed char> && + !std::is_same_v, unsigned char>; +template +concept contiguous_float_array = + contiguous_number_array && + std::is_floating_point_v> && + sizeof(std::ranges::range_value_t) <= sizeof(uint64_t); + +// Most bytes one element writes, the comma before it included. A double +// takes at most 24 characters (-d.dddddddddddddddde-308). +template +constexpr size_t max_element_size() { + if constexpr (std::is_floating_point_v) { + return 24 + 1; + } else { + return size_t(std::numeric_limits::digits10) + 1 + std::is_signed_v + 1; + } +} +// The number writers may write scratch bytes past the end of the number. +constexpr size_t write_slack = simdjson::internal::to_chars_buffer_size; +// Arrays whose bound fits are written on the stack, then copied once. +constexpr size_t stack_buffer_size = 1024; + +template +simdjson_inline char *write_element(char *p, T v) noexcept { + if constexpr (std::is_floating_point_v) { + return simdjson::rvv_vls::builder::internal::write_double(p, double(v)); + } else if constexpr (std::is_unsigned_v) { + return simdjson::internal::write_uint(p, static_cast(v)); + } else { + using U = std::make_unsigned_t; + const bool negative = v < 0; + U pv = negative ? U(0) - static_cast(v) : static_cast(v); + *p = '-'; + p += negative; + return simdjson::internal::write_uint(p, static_cast(pv)); + } +} + +template +simdjson_inline char *write_array(char *p, const T *data, size_t n) noexcept { + *p++ = '['; + if (n) { + p = write_element(p, data[0]); + for (size_t i = 1; i < n; i++) { + *p++ = ','; + p = write_element(p, data[i]); + } + } + *p++ = ']'; + return p; +} + +// Not simdjson_inline: MSVC cannot force-inline a function with a try block (C4714). +inline bool assign_bytes(std::string &s, const char *data, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + s.assign(data, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + // Without exceptions, a failed allocation terminates the program. + s.assign(data, n); +#endif + return true; +} + +inline bool resize_for_direct_write(std::string &s, size_t n) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + simdjson::rvv_vls::builder::internal::resize_uninitialized(s, n); + } catch (...) { // std::bad_alloc + return false; + } +#else + simdjson::rvv_vls::builder::internal::resize_uninitialized(s, n); +#endif + return true; +} + +// A result that fills at most half of the allocation is copied out, as in +// string_builder::move_to. On failure s keeps the larger buffer. +simdjson_never_inline void shrink_to_size(std::string &s) noexcept { +#if defined(__cpp_exceptions) || defined(_CPPUNWIND) + try { + std::string(s).swap(s); + } catch (...) { // std::bad_alloc + } +#else + std::string(s).swap(s); +#endif +} + +template +simdjson_warn_unused error_code to_json_array(const T *data, size_t n, std::string &s) noexcept { + constexpr size_t per = max_element_size(); + if (simdjson_unlikely(n > (size_t(-1) - 2 - write_slack) / per)) { + return MEMALLOC; + } + const size_t bound = n * per + 2 + write_slack; + if (bound <= stack_buffer_size) { + simdjson_indeterminate char buffer[stack_buffer_size]; + char *end = write_array(buffer, data, n); + return assign_bytes(s, buffer, size_t(end - buffer)) ? SUCCESS : MEMALLOC; + } + const size_t old_capacity = s.capacity(); + if (!resize_for_direct_write(s, bound)) { + return MEMALLOC; + } + char *begin = &s[0]; + const size_t used = size_t(write_array(begin, data, n) - begin); + s.resize(used); + // A string that could already hold the result is being reused: keep its + // buffer so the next call does not allocate again. + if (old_capacity < used && used <= s.capacity() / 2) { + shrink_to_size(s); + } + return SUCCESS; +} +} // namespace builder_to_json_detail +#endif // SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + +template +simdjson_warn_unused error_code to_json(const Z &z, std::string &s, size_t initial_capacity) { +#if SIMDJSON_SUPPORTS_RANGES && SIMDJSON_SUPPORTS_CONCEPTS + if constexpr (builder_to_json_detail::contiguous_int_array || + builder_to_json_detail::contiguous_float_array) { + (void)initial_capacity; + return builder_to_json_detail::to_json_array(std::ranges::data(z), size_t(std::ranges::size(z)), s); + } else +#endif + { + simdjson::rvv_vls::builder::string_builder b(initial_capacity); + simdjson::rvv_vls::builder::internal::append_value(b, z); + return b.move_to(s); + } +} + +template +simdjson_warn_unused simdjson_result to_json(const Z &z, size_t initial_capacity) { + std::string s; + auto e = to_json(z, s, initial_capacity); + if (e) { return e; } + return s; +} + +} // namespace simdjson +#endif // !SIMDJSON_STATIC_REFLECTION + #endif // SIMDJSON_GENERIC_STRING_BUILDER_INL_H /* end file simdjson/generic/builder/json_string_builder-inl.h for rvv_vls */ @@ -70536,6 +75732,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -70550,14 +75747,11 @@ namespace arm64 { namespace numberparsing { // we don't have SSE, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -70601,6 +75795,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/arm64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/arm64/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -70749,6 +75944,26 @@ namespace { static simdjson_inline uint8x16_t splat(uint8_t _value) { return vmovq_n_u8(_value); } static simdjson_inline uint8x16_t zero() { return vdupq_n_u8(0); } static simdjson_inline uint8x16_t load(const uint8_t* values) { return vld1q_u8(values); } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline uint8x16_t load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const uint8x16_t window = vld1q_u8(ptr + n - 16); + const uint8x16_t shuffle = vld1q_u8(internal::shift_tail_mask + 16 - n); + // vqtbl1q_u8 zeroes the bytes whose index is out of range. + const uint8x16_t filler = vandq_u8(vcgeq_u8(shuffle, vdupq_n_u8(16)), vdupq_n_u8(fill)); + return vorrq_u8(vqtbl1q_u8(window, shuffle), filler); + } +#if SIMDJSON_IS_BIG_ENDIAN + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return vld1q_u8(block); +#else + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return vcombine_u8(vcreate_u8(lo), vcreate_u8(hi)); +#endif + } simdjson_inline simd8(const uint8x16_t _value) : base_u8(_value) {} // Zero constructor @@ -72613,6 +77828,23 @@ class value { */ simdjson_inline std::string_view raw_json_token() noexcept; + /** + * Calls the visitor for this value and everything in it, as document::visit() does for a + * whole document, for example after navigating to a field: + * + * auto error = doc["payload"].visit(visitor); + * + * The value must not have been read. The walk does not move the iterator: to go on, read the + * value or the next field or element as usual. A string with escapes is valid until you read + * the document further or visit again. The maximal depth counts from the root of the document. + * A value at the root also fails if anything follows it. + * + * @returns SUCCESS, OUT_OF_ORDER_ITERATION if the value has been read, the first error found + * in the value, or the first error the visitor returns. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); + /** * Get a string_view pointing at this value in the JSON document. * If this element is an array or an object, it consumes the array or the object @@ -72930,6 +78162,8 @@ struct simdjson_result : public arm64::implementation_si /** @copydoc simdjson_inline std::string_view value::raw_json_token() const noexcept */ simdjson_inline simdjson_result raw_json_token() noexcept; simdjson_inline simdjson_result raw_json() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** @copydoc simdjson_inline simdjson_result current_location() noexcept */ simdjson_inline simdjson_result current_location() noexcept; @@ -73275,6 +78509,29 @@ class json_iterator { simdjson_inline error_code out_of_place_error() noexcept; /** Tells whether the string before pos, followed by a colon, is a key. */ static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; + /** + * Validates the array or object at the current position and everything in it, without + * recursion. Outside of streaming mode, it also checks that nothing follows it. It does + * not move the iterator. + */ + simdjson_warn_unused error_code validate_container() noexcept; + static simdjson_inline bool has_backslash(const uint8_t *src, size_t len) noexcept; + /** + * Calls the visitor for the array or object at the start position and everything in it, + * without recursion (see document::visit()). The container is at depth parent_depth + 1. At + * the root (parent_depth == 0) and outside of streaming mode, it also checks that nothing + * follows it. It does not move the iterator. Escaped strings are copied into the string + * buffer. + */ + template + simdjson_warn_unused error_code visit_container(V &visitor, token_position start, size_t parent_depth); + template + simdjson_warn_unused simdjson_inline error_code visit_string(const uint8_t *quote, bool key, V &visitor); + template + simdjson_warn_unused simdjson_inline error_code visit_scalar(const uint8_t *src, V &visitor); + /** Calls the visitor for a number that numberparsing::parse_number accepted. */ + template + static simdjson_warn_unused simdjson_inline error_code visit_number(const number &value, const char *raw, V &visitor); /** * Tell whether the iterator is still at the start @@ -73464,7 +78721,8 @@ class json_iterator { /** * Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with * N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero. - * Trailing whitespace, commas, and record separators (0x1E) do not count toward max_len. + * Trailing whitespace does not count toward max_len. A comma or record + * separator (0x1E) is ignored only for a document stream. * The buffer (tmpbuf) is padded with space characters. */ simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept; @@ -74160,6 +79418,33 @@ class parser { */ simdjson_warn_unused simdjson_result iterate_raw(padded_string_view json) & noexcept; + /** + * Parses the document and walks it once with the visitor: the same as iterate() followed by + * document::visit(), with the same values and, when the visitor returns SUCCESS, the same + * error code, but faster on small documents. + * + * counting_visitor visitor; + * auto error = parser.visit(R"({"stars":[1,2,3]})"_padded, visitor); + * + * A document of at most MAX_ONE_PASS_VISIT bytes whose root is an object or an array is read in + * a single pass, without the structural index that iterate() builds. Some checks, such as the + * UTF-8 validation, then come at the end of the walk: on an invalid document, the visitor may + * have seen part or all of it before visit() returns the error code of document::visit(), and + * an error returned by the visitor may come first. With SIMDJSON_ENABLE_NAN_INF or + * SIMDJSON_ALLOW_TRAILING_COMMAS, there is no one-pass walk. + * + * See document::visit() for the methods of the visitor and the lifetime of the strings. + * + * @param json The JSON to parse, with at least SIMDJSON_PADDING bytes after it. + * @param visitor The visitor. + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(padded_string_view json, V &visitor) &; + /** Documents of at most this many bytes may be visited in one pass, see visit(). */ + static constexpr size_t MAX_ONE_PASS_VISIT = 32; + /** * Parse a buffer containing many JSON documents. @@ -74318,6 +79603,20 @@ class parser { */ simdjson_pure simdjson_inline size_t max_depth() const noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the string buffer and the structural indexes) through a buffer_allocator. + * nullptr, the default, uses new[]. The allocator must outlive the parser. + * + * Buffers that the parser already holds keep the allocator that allocated + * them until the parser grows them, so set the allocator before the first + * document or the first call to allocate(). A failed allocation makes the + * parser return MEMALLOC and leaves its buffers as they were. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + /** * Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length * and `max_depth` depth. @@ -74427,17 +79726,27 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr& get_threadlocal_parser_if_exists(); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + simdjson_inline void drop_trailing_commas(const uint8_t *buf) noexcept; +#endif #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** + * The one-pass walk of visit(). Returns UNINITIALIZED when it does not handle the document, + * and TAPE_ERROR when the document is invalid. visitor_failed tells an error of the visitor. + */ + template + simdjson_warn_unused simdjson_inline error_code visit_one_pass(const uint8_t *buf, size_t len, V &visitor, bool &visitor_failed); /** @private [for benchmarking access] The implementation to use */ std::unique_ptr implementation{}; size_t _capacity{0}; size_t _max_capacity; size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; - std::unique_ptr string_buf{}; + simdjson::internal::allocated_array string_buf{}; + const buffer_allocator *_allocator{nullptr}; #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; @@ -75695,6 +81004,58 @@ class document { * left as is. */ inline void rewind() noexcept; + /** + * Validates the whole document: its structure, every string (escapes included), every + * number, true, false and null, and that nothing follows the root value. Strings are + * checked as get_string() checks them and numbers as get_double() does. The document is + * rewound before and after, so that it can be iterated after a successful validation. + * + * It is faster than iterating through every value, because it walks the tokens directly, + * without creating values, arrays or objects. + * + * @returns SUCCESS if the document is valid, or the error found first. + */ + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + /** + * Walks the whole document once and calls the visitor for each value, in document order. + * Use it to build your own representation of the document (a tree, columns, ...) faster + * than by iterating, as the walk creates no values, arrays or objects. + * + * The visitor provides these methods. Each returns an error_code: anything but SUCCESS stops + * the walk, and visit() returns it. + * + * error_code on_object_start(); + * error_code on_object_end(uint32_t member_count); + * error_code on_array_start(); + * error_code on_array_end(uint32_t element_count); + * error_code on_key(std::string_view key); // before each member value + * error_code on_string(std::string_view value); + * error_code on_int64(int64_t value, const char *raw); // integers that fit an int64_t + * error_code on_uint64(uint64_t value, const char *raw); // larger positive integers + * error_code on_double(double value, const char *raw); + * error_code on_bool(bool value); + * error_code on_null(); + * + * raw points at the number in the document, so that the visitor can tell -0 from 0, for + * example. As with the DOM parser, an integer that does not fit in 64 bits is a BIGINT_ERROR. + * + * A key or a string without escapes is a view into the document: it is valid as long as the + * document's bytes are. A key or a string with escapes is unescaped into the parser: it is + * valid until the document is iterated or visited again, or the parser parses another + * document. + * + * visit() succeeds exactly when the DOM parser does. An error may come after the visitor has + * seen part of the document. The document is rewound before and after the walk, so that it + * can be iterated afterwards. The visitor may throw: the exception goes through visit(), and + * the document must then be rewound before it is used again. + * + * To parse and visit a document in one call, faster on small documents, see parser::visit(). + * + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** * Returns debugging information. */ @@ -75865,6 +81226,9 @@ class document { simdjson_inline value_iterator resume_value_iterator() noexcept; simdjson_inline value_iterator get_root_value_iterator() noexcept; + /** The walk of visit(), between its two rewinds. */ + template + simdjson_warn_unused simdjson_inline error_code visit_root(V &visitor); simdjson_inline simdjson_result start_or_resume_object() noexcept; static simdjson_inline document start(ondemand::json_iterator &&iter) noexcept; @@ -76084,6 +81448,9 @@ struct simdjson_result : public arm64::implementation simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); simdjson_inline simdjson_result get_array() & noexcept; simdjson_inline simdjson_result get_object() & noexcept; @@ -79371,6 +84738,7 @@ inline std::ostream& operator<<(std::ostream& out, simdjson::simdjson_result #include +#include #if SIMDJSON_STATIC_REFLECTION #include #include @@ -79580,9 +84948,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { SIMDJSON_TRY(v.get(scratch.elements.emplace_back())); release.parsed++; } - out.reserve(release.parsed); - release.complete = true; - for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + if constexpr (std::is_trivially_copyable_v) { + out.assign(scratch.elements.begin(), scratch.elements.end()); + release.complete = true; + } else if (sizeof(value_type) <= 32 && scratch.elements.capacity() / 2 < release.parsed) { + // Hand the buffer over only when it is at least half full, so that out + // does not keep the capacity of an earlier, larger array. Swapping + // large structs is slower than moving them (recipe_book benchmark). + size_t const capacity = scratch.elements.capacity(); + out.swap(scratch.elements); + release.complete = true; + if (capacity * sizeof(value_type) <= (1 << 20)) { scratch.elements.reserve(capacity); } + } else { + out.reserve(release.parsed); + release.complete = true; + for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + } return SUCCESS; } } @@ -79812,7 +85193,11 @@ consteval void append_eligible_fields(std::meta::info type, std::vector(std::meta::substitute(^^flattenable_type, {flattened}))) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member whose type is a structure deserialized member by member", mem); +#else + simdjson::detail::flatten_requires_a_member_deserialized_member_by_member(); +#endif } append_eligible_fields(flattened, prefix, fields); } else { @@ -81168,6 +86553,27 @@ simdjson_warn_unused simdjson_inline simdjson_result value::get_number() return iter.get_number(); } +template +simdjson_warn_unused simdjson_inline error_code value::visit(V &visitor) { + if (!iter.is_at_start()) { return OUT_OF_ORDER_ITERATION; } + json_iterator &json_iter = iter.json_iter(); + const uint8_t *const json = iter.peek_start(); + // The escaped strings of the value go where reading it would put them, so that the string + // buffer has room for them however many times the value is visited. + uint8_t *const string_buf_loc = json_iter._string_buf_loc; + error_code error; + switch (*json) { + case '{': case '[': + error = json_iter.visit_container(visitor, iter.start_position(), size_t(iter.depth() - 1)); + break; + // A scalar value is nested in a container: its parser reads inside the document. + case '"': error = json_iter.visit_string(json, false, visitor); break; + default: error = json_iter.visit_scalar(json, visitor); break; + } + json_iter._string_buf_loc = string_buf_loc; + return error; +} + simdjson_inline std::string_view value::raw_json_token() noexcept { return std::string_view(reinterpret_cast(iter.peek_start()), iter.peek_start_length()); } @@ -81579,6 +86985,12 @@ simdjson_inline simdjson_result::operator bool() noexcep } #endif +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + simdjson_inline simdjson_result simdjson_result::raw_json_token() noexcept { if (error()) { return error(); } return first.raw_json_token(); @@ -81674,6 +87086,124 @@ inline void document::rewind() noexcept { static_cast(iter.rewind()); } +simdjson_warn_unused simdjson_inline error_code document::validate() noexcept { + SIMDJSON_TRY(iter.rewind()); + const bool check_trailing = !iter.streaming(); + const uint8_t first = *iter.peek(); + error_code error; + switch (first) { + case '{': case '[': + error = iter.validate_container(); + break; + case '"': + error = get_root_value_iterator().get_root_string(check_trailing, false).error(); + break; + case 't': case 'f': + error = get_root_value_iterator().get_root_bool(check_trailing).error(); + break; + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && !null_value) { error = N_ATOM_ERROR; } +#if SIMDJSON_ENABLE_NAN_INF + if (error && !get_root_value_iterator().get_root_double(check_trailing).error()) { error = SUCCESS; } +#endif + break; + } + default: + error = get_root_value_iterator().get_root_double(check_trailing).error(); + break; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit(V &visitor) { + SIMDJSON_TRY(iter.rewind()); + const error_code error = visit_root(visitor); + // The strings of the walk stay in the buffer, but an iteration may start from its beginning. + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit_root(V &visitor) { + const bool check_trailing = !iter.streaming(); + const uint8_t *const first = iter.peek(); + const char *const raw = reinterpret_cast(first); + error_code error; + switch (*first) { + case '{': case '[': + return iter.visit_container(visitor, iter.position(), 0); + case '"': { + raw_json_string text; + error = get_root_value_iterator().get_root_raw_json_string(check_trailing).get(text); + if (!error) { return iter.visit_string(first, false, visitor); } + break; + } + case 't': case 'f': { + bool value; + error = get_root_value_iterator().get_root_bool(check_trailing).get(value); + if (!error) { return visitor.on_bool(value); } + break; + } + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && null_value) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + double value; + if (!get_root_value_iterator().get_root_double(check_trailing).get(value)) { return visitor.on_double(value, raw); } +#endif + if (!error) { error = N_ATOM_ERROR; } + break; + } + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + number value; + error = get_root_value_iterator().get_root_number(check_trailing).get(value); + if (!error) { return json_iterator::visit_number(value, raw, visitor); } + break; + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': { + double value; + error = get_root_value_iterator().get_root_double(check_trailing).get(value); + if (!error) { return visitor.on_double(value, raw); } + return error == TRAILING_CONTENT ? error : TAPE_ERROR; + } +#endif + default: + return TAPE_ERROR; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (*first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + return error; +} + inline std::string document::to_debug_string() noexcept { return iter.to_string(); } @@ -82228,6 +87758,16 @@ simdjson_inline error_code simdjson_result::rewind() first.rewind(); return SUCCESS; } +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + +simdjson_warn_unused simdjson_inline error_code simdjson_result::validate() noexcept { + if (error()) { return error(); } + return first.validate(); +} simdjson_inline simdjson_result simdjson_result::begin() & noexcept { if (error()) { return error(); } return first.begin(); @@ -83298,6 +88838,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } worker->start_thread(); @@ -83551,6 +89092,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch @@ -83566,6 +89110,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -83907,6 +89454,8 @@ simdjson_inline simdjson_result simdjson_result= 8; src += 8, len -= 8) { + std::memcpy(&word, src, sizeof(word)); + word ^= BACKSLASHES; + if ((word - ONES) & ~word & HIGHS) { return true; } + } + uint64_t keep; + std::memcpy(&keep, KEEP + 8 - len, sizeof(keep)); + std::memcpy(&word, src, sizeof(word)); + word = (word ^ BACKSLASHES) | ~keep; + return ((word - ONES) & ~word & HIGHS) != 0; +} + +simdjson_warn_unused simdjson_never_inline error_code json_iterator::validate_container() noexcept { + const uint8_t *const json = token.buf; + token_position pos = token.position(); + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // One bit per depth tells whether the container at that depth is an array. Deeper than + // the fixed stack allows, the bits move to the heap. + uint64_t fixed_stack[16]{}; + std::unique_ptr heap_stack; + uint64_t *is_array = fixed_stack; + size_t depth = 0; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VALIDATE_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VALIDATE_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': goto scalar_string; + default: goto scalar; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. Its bit may then + // be at max_depth, which the stack has room for. + if (++depth >= max_depth && (pos == end || json[*pos] != c + 2)) { return DEPTH_ERROR; } + // The bits move once: the next time this depth is reached, the heap holds the current + // bits and the fixed stack holds stale ones. + if (depth == sizeof(fixed_stack) * 8 && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint64_t[max_depth / 64 + 1]()); + if (!heap_stack) { return MEMALLOC; } + std::memcpy(heap_stack.get(), fixed_stack, sizeof(fixed_stack)); + is_array = heap_stack.get(); + } + if (c == '[') { + is_array[depth / 64] |= uint64_t(1) << (depth % 64); + SIMDJSON_VALIDATE_NEXT(); + if (c == ']') { goto container_end; } + goto value; + } + is_array[depth / 64] &= ~(uint64_t(1) << (depth % 64)); + SIMDJSON_VALIDATE_NEXT(); + if (c == '}') { goto container_end; } + goto key; + +key: + if (c != '"') { return TAPE_ERROR; } + // A string is valid once stage 1 has accepted the document, unless it holds an escape. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + SIMDJSON_VALIDATE_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VALIDATE_NEXT(); + goto value; + +scalar_string: + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + goto value_end; + +scalar: + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + break; + default: + return TAPE_ERROR; + } + // The scalar is not the last token, so the parsers read inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + switch (c) { + case 't': if (!atomparsing::is_valid_true_atom(json + index)) { return T_ATOM_ERROR; } break; + case 'f': if (!atomparsing::is_valid_false_atom(json + index)) { return F_ATOM_ERROR; } break; + case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (!atomparsing::is_valid_null_atom(json + index) && !atomparsing::is_valid_nan_atom(json + index)) { return N_ATOM_ERROR; } +#else + if (!atomparsing::is_valid_null_atom(json + index)) { return N_ATOM_ERROR; } +#endif + break; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': if (!atomparsing::is_valid_nan_atom(json + index)) { return TAPE_ERROR; } break; + case 'i': case 'I': if (!atomparsing::is_valid_inf_atom(json + index)) { return TAPE_ERROR; } break; +#endif + default: + if (numberparsing::parse_double(json + index).error()) { return NUMBER_ERROR; } + break; + } + +value_end: + SIMDJSON_VALIDATE_NEXT(); + if (c == ',') { + SIMDJSON_VALIDATE_NEXT(); + if (is_array[depth / 64] & (uint64_t(1) << (depth % 64))) { goto value; } + goto key; + } + if (c != (is_array[depth / 64] & (uint64_t(1) << (depth % 64)) ? ']' : '}')) { return TAPE_ERROR; } + +container_end: + if (--depth > 0) { goto value_end; } +#undef SIMDJSON_VALIDATE_NEXT + if (!streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_number(const number &value, const char *raw, V &visitor) { + switch (value.get_number_type()) { + case number_type::signed_integer: return visitor.on_int64(value.get_int64(), raw); + case number_type::unsigned_integer: return visitor.on_uint64(value.get_uint64(), raw); + case number_type::floating_point_number: return visitor.on_double(value.get_double(), raw); + default: return BIGINT_ERROR; + } +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_string(const uint8_t *quote, bool key, V &visitor) { + const uint8_t *const start = quote + 1; + // A string without escapes is passed as it is in the document. + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (const uint8_t *src = start;; src += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(src, scratch); + if (bs_quote.has_quote_first()) { + std::string_view text(reinterpret_cast(start), size_t(src - start) + size_t(bs_quote.quote_index())); + return key ? visitor.on_key(text) : visitor.on_string(text); + } + if (bs_quote.has_backslash()) { break; } + } + uint8_t *const end = parser->implementation->parse_string(start, _string_buf_loc, false); + if (!end) { return STRING_ERROR; } + std::string_view text(reinterpret_cast(_string_buf_loc), size_t(end - _string_buf_loc)); + _string_buf_loc = end; + return key ? visitor.on_key(text) : visitor.on_string(text); +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_scalar(const uint8_t *src, V &visitor) { + switch (*src) { + case 't': return atomparsing::is_valid_true_atom(src) ? visitor.on_bool(true) : T_ATOM_ERROR; + case 'f': return atomparsing::is_valid_false_atom(src) ? visitor.on_bool(false) : F_ATOM_ERROR; + case 'n': + if (atomparsing::is_valid_null_atom(src)) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } +#endif + return N_ATOM_ERROR; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + number value; + SIMDJSON_TRY(numberparsing::parse_number(src, value)); + return visit_number(value, reinterpret_cast(src), visitor); + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } + return TAPE_ERROR; + case 'i': case 'I': + if (atomparsing::is_valid_inf_atom(src)) { return visitor.on_double(std::numeric_limits::infinity(), reinterpret_cast(src)); } + return TAPE_ERROR; +#endif + default: + return TAPE_ERROR; + } +} + +template +simdjson_warn_unused error_code json_iterator::visit_container(V &visitor, token_position start, size_t parent_depth) { + const uint8_t *const json = token.buf; + token_position pos = start; + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // For each open container, the number of its elements so far, with the top bit set for an + // array. Deeper than the fixed stack allows, the stack moves to the heap. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + constexpr size_t FIXED_DEPTH = 64; + uint32_t fixed_stack[FIXED_DEPTH]; + std::unique_ptr heap_stack; + uint32_t *stack = fixed_stack; + size_t depth = parent_depth; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VISIT_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VISIT_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': + // A string is not the last token, so that its closing quote is inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, false, visitor)); + goto value_end; + default: + // The scalar is not the last token, so the parsers read inside the document. + if (simdjson_unlikely(pos == end)) { + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + return INCOMPLETE_ARRAY_OR_OBJECT; + default: + return TAPE_ERROR; + } + } + SIMDJSON_TRY(visit_scalar(json + index, visitor)); + goto value_end; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. + if (pos != end && json[*pos] == c + 2) { + pos++; + if (c == '[') { + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_TRY(visitor.on_array_end(0)); + } else { + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_TRY(visitor.on_object_end(0)); + } + if (depth == parent_depth) { goto document_end; } + goto value_end; + } + if (++depth >= max_depth) { return DEPTH_ERROR; } + // Copy the fixed stack once. A later container at this depth must keep the + // counts already stored on the heap. + if (depth >= FIXED_DEPTH && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint32_t[max_depth]); + if (!heap_stack) { return MEMALLOC; } + // Only the slots past the parent were written. + if (parent_depth + 1 < FIXED_DEPTH) { + std::memcpy(heap_stack.get() + parent_depth + 1, fixed_stack + parent_depth + 1, (FIXED_DEPTH - parent_depth - 1) * sizeof(fixed_stack[0])); + } + stack = heap_stack.get(); + } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_VISIT_NEXT(); + goto value; + } + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_VISIT_NEXT(); + +key: + if (c != '"') { return TAPE_ERROR; } + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, true, visitor)); + SIMDJSON_VISIT_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VISIT_NEXT(); + goto value; + +value_end: + SIMDJSON_VISIT_NEXT(); + if (c == ',') { + stack[depth]++; + SIMDJSON_VISIT_NEXT(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_object_end(stack[depth])); + } + if (--depth > parent_depth) { goto value_end; } + +document_end: +#undef SIMDJSON_VISIT_NEXT + if (parent_depth == 0 && !streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + simdjson_inline bool json_iterator::at_root() const noexcept { return position() == root_position(); } @@ -84547,10 +90425,20 @@ simdjson_warn_unused simdjson_inline bool json_iterator::copy_to_buffer(const ui // peek_root_length() stops at the next structural index. Stage 1 omits the // comma or RS (0x1E) that separates stream documents, so that byte and the // whitespace around it remain in the span. RS is not a valid number finisher. + // Outside of a stream, the comma and RS are not separators: some kernels + // keep RS in the scalar token, and dropping it would accept "1\x1e". while (max_len > 0) { const uint8_t last = json[max_len - 1]; + // iterate_allow_incomplete_json() reuses _streaming, so a root scalar + // there is not a document_stream. +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + const bool separator = _streaming && !_allow_incomplete_json && + (last == ',' || last == 0x1E); +#else + const bool separator = _streaming && (last == ',' || last == 0x1E); +#endif if (last != ' ' && last != '\t' && last != '\n' && last != '\r' && - last != ',' && last != 0x1E) { + !separator) { break; } max_len--; @@ -85980,22 +91868,22 @@ simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capa return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - std::unique_ptr new_string_buf(new (std::nothrow) uint8_t[string_capacity]); - if (!new_string_buf) { return MEMALLOC; } + simdjson::internal::allocated_array new_string_buf; + if (!new_string_buf.allocate(string_capacity, _allocator)) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr new_start_positions(new (std::nothrow) token_position[new_max_depth]); if (!new_start_positions) { return MEMALLOC; } #endif - if (implementation) { - error_code err = implementation->allocate(new_capacity, new_max_depth); - if (err) { return err; } - } else { - error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, new_max_depth, implementation); if (err) { implementation.reset(); return err; } } + implementation->allocator = _allocator; + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } string_buf = std::move(new_string_buf); #if SIMDJSON_DEVELOPMENT_CHECKS start_positions = std::move(new_start_positions); @@ -86024,9 +91912,42 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iterate(p // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return document::start({ reinterpret_cast(json.data()), this }); } +// Removes from the structural indexes each comma that follows a value and +// precedes a closing bracket, so that the iterator never sees it. The entries +// past the last index (stage 1 keeps up to three there) move with the others. +#if SIMDJSON_ALLOW_TRAILING_COMMAS +simdjson_inline void parser::drop_trailing_commas(const uint8_t *buf) noexcept { + uint32_t *indexes = implementation->structural_indexes.get(); + const uint32_t n = implementation->n_structural_indexes; + uint32_t kept = 0; + uint8_t previous = '['; + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = buf[indexes[i]]; + if (c == ',' && i + 1 < n && previous != '[' && previous != '{' && previous != ',' && previous != ':') { + const uint8_t next = buf[indexes[i + 1]]; + if (next == ']' || next == '}') { + previous = c; + continue; + } + } + indexes[kept++] = indexes[i]; + previous = c; + } + if (kept != n) { + indexes[kept] = indexes[n]; + indexes[kept + 1] = indexes[n + 1]; + indexes[kept + 2] = indexes[n + 2]; + implementation->n_structural_indexes = kept; + } +} +#endif // SIMDJSON_ALLOW_TRAILING_COMMAS + #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_warn_unused simdjson_inline simdjson_result parser::iterate_allow_incomplete_json(padded_string_view json) & noexcept { if (!json.has_sufficient_padding()) { return INSUFFICIENT_PADDING; } @@ -86130,9 +92051,210 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iter // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return json_iterator(reinterpret_cast(json.data()), this); } +namespace { +struct ignoring_visitor { + simdjson_inline error_code on_object_start() { return SUCCESS; } + simdjson_inline error_code on_object_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_array_start() { return SUCCESS; } + simdjson_inline error_code on_array_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_key(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_string(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_int64(int64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_uint64(uint64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_double(double, const char *) { return SUCCESS; } + simdjson_inline error_code on_bool(bool) { return SUCCESS; } + simdjson_inline error_code on_null() { return SUCCESS; } +}; +} // unnamed namespace + +template +simdjson_warn_unused simdjson_inline error_code parser::visit(padded_string_view json, V &visitor) & { +#if !SIMDJSON_ENABLE_NAN_INF && !SIMDJSON_ALLOW_TRAILING_COMMAS + if (json.length() <= MAX_ONE_PASS_VISIT && json.has_sufficient_padding()) { + if (capacity() < json.length() || !string_buf) { + SIMDJSON_TRY( allocate(json.length(), max_depth()) ); + } + bool visitor_failed = false; + const error_code error = visit_one_pass(reinterpret_cast(json.data()), json.length(), visitor, visitor_failed); + if (error != UNINITIALIZED) { + if (error != TAPE_ERROR || visitor_failed) { return error; } + // The visitor has already seen part of the document: the regular walk only finds the + // error code, and never calls the visitor a second time. + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + ignoring_visitor ignoring; + const error_code regular_error = doc.visit(ignoring); + return regular_error ? regular_error : TAPE_ERROR; + } + } +#endif + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + return doc.visit(visitor); +} + +// A single pass over the bytes, for small documents. The root must be an array or an object, and +// the last byte that is not whitespace must be ] or }: before it, runs of whitespace, digits or +// atoms stop without a bound check. Only a closing bracket or a string may reach the end. +template +simdjson_warn_unused simdjson_inline error_code parser::visit_one_pass(const uint8_t *const buf, const size_t len, V &visitor, bool &visitor_failed) { + const auto is_whitespace = [](uint8_t c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; + if (len == 0 || len > MAX_ONE_PASS_VISIT) { return UNINITIALIZED; } + const uint8_t *p = buf; + const uint8_t *last = buf + len - 1; + while (p < last && is_whitespace(*p)) { p++; } + while (last > p && is_whitespace(*last)) { last--; } + if ((*p != '{' && *p != '[') || (*last != '}' && *last != ']')) { return UNINITIALIZED; } + const uint8_t *const end = last + 1; + uint8_t *dst = string_buf.get(); + bool non_ascii = false; + // For each open container, the number of its elements so far, with the top bit set for an + // array. Each container opens at a distinct byte before the last one, so that the depth stays + // below MAX_ONE_PASS_VISIT. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + uint32_t stack[MAX_ONE_PASS_VISIT]; + size_t depth = 0; + uint8_t c = *p; + +#define SIMDJSON_ONE_PASS_CALL(EXPR) \ + do { \ + const error_code one_pass_error = (EXPR); \ + if (simdjson_unlikely(one_pass_error != SUCCESS)) { visitor_failed = true; return one_pass_error; } \ + } while (0) +#define SIMDJSON_ONE_PASS_WHITESPACE() while (is_whitespace(*p)) { p++; } +// The string at p, which is left past the closing quote. +#define SIMDJSON_ONE_PASS_STRING(METHOD) \ + do { \ + const uint8_t *const start = ++p; \ + bool escaped = false; \ + for (;; p++) { \ + if (simdjson_unlikely(p >= end)) { return TAPE_ERROR; } \ + if (*p == '"') { break; } \ + if (*p == '\\') { \ + escaped = true; \ + p++; \ + } else if (simdjson_unlikely(*p < 0x20)) { \ + return TAPE_ERROR; \ + } else if (*p >= 0x80) { \ + non_ascii = true; \ + } \ + } \ + std::string_view text(reinterpret_cast(start), size_t(p - start)); \ + p++; \ + if (escaped) { \ + uint8_t *const unescaped_end = implementation->parse_string(start, dst, false); \ + if (unescaped_end == nullptr) { return TAPE_ERROR; } \ + text = std::string_view(reinterpret_cast(dst), size_t(unescaped_end - dst)); \ + dst = unescaped_end; \ + } \ + SIMDJSON_ONE_PASS_CALL(visitor.METHOD(text)); \ + } while (0) + + goto container_start; + +value: + switch (*p) { + case '{': case '[': + c = *p; + goto container_start; + case '"': + SIMDJSON_ONE_PASS_STRING(on_string); + goto value_end; + case 't': + if (!atomparsing::is_valid_true_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(true)); + p += 4; + goto value_end; + case 'f': + if (!atomparsing::is_valid_false_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(false)); + p += 5; + goto value_end; + case 'n': + if (!atomparsing::is_valid_null_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_null()); + p += 4; + goto value_end; + default: { + number value; + if (numberparsing::parse_number(p, value) != SUCCESS) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(json_iterator::visit_number(value, reinterpret_cast(p), visitor)); + while (jsoncharutils::is_not_structural_or_whitespace(*p)) { p++; } + goto value_end; + } + } + +container_start: + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + // As in DOM, an empty container does not count toward the maximal depth. + if (*p == c + 2) { + p++; + if (c == '[') { + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(0)); + } else { + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(0)); + } + if (depth == 0) { goto document_end; } + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + if (++depth >= max_depth()) { return TAPE_ERROR; } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + goto value; + } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + +key: + if (*p != '"') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_STRING(on_key); + SIMDJSON_ONE_PASS_WHITESPACE(); + if (*p != ':') { return TAPE_ERROR; } + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + goto value; + +value_end: + SIMDJSON_ONE_PASS_WHITESPACE(); + c = *p++; + if (c == ',') { + stack[depth]++; + SIMDJSON_ONE_PASS_WHITESPACE(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(stack[depth])); + } + if (--depth > 0) { + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + +document_end: +#undef SIMDJSON_ONE_PASS_CALL +#undef SIMDJSON_ONE_PASS_WHITESPACE +#undef SIMDJSON_ONE_PASS_STRING + if (p != end) { return TAPE_ERROR; } + if (non_ascii && !simdjson::validate_utf8(reinterpret_cast(buf), len)) { return TAPE_ERROR; } + return SUCCESS; +} + inline simdjson_result parser::iterate_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept { if(batch_size < MINIMAL_BATCH_SIZE) { batch_size = MINIMAL_BATCH_SIZE; } if((len >= 3) && (std::memcmp(buf, "\xEF\xBB\xBF", 3) == 0)) { @@ -86250,6 +92372,13 @@ simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return _max_depth; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} + simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept { if(max_capacity > dom::MINIMAL_DOCUMENT_CAPACITY) { _max_capacity = max_capacity; @@ -86769,13 +92898,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_objec _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing } at end"); } - // If the last character is } *and* the first gibberish character is also '}' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is } *and* the first gibberish character is '}', ']' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == '}') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed object. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -87179,13 +93310,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_array _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing ] at end"); } - // If the last character is ] *and* the first gibberish character is also ']' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is ] *and* the first gibberish character is ']', '}' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == ']') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed array. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -87355,7 +93488,7 @@ simdjson_inline simdjson_result value_iterator::get_root_num // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -87379,7 +93512,7 @@ simdjson_inline simdjson_result value_iterator::get_root_number(bool che // number: -0.e-308. // NOTE: the current approach doesn't work for very big integer numbers containing more than 1074 digits. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -87461,7 +93594,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::g simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer tmpbuf[20+1] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+1)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 20 characters"); @@ -87478,7 +93611,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::ge simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64_in_string(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer tmpbuf[20+2] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+2)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 22 characters"); @@ -87499,7 +93632,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -87521,7 +93654,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -87543,7 +93676,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ // digits that matter is smaller for binary32, but the JSON document may still // spell out a long number that we must parse (and round) faithfully. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -87562,7 +93695,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ auto max_len = peek_root_length(); auto json = peek_root_scalar("float"); // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -87900,6 +94033,9 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '"': return json_type::string; case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } +#endif return json_type::null; case 't': case 'f': return json_type::boolean; @@ -87907,6 +94043,14 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return json_type::number; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; + case 'I': case 'i': + if (atomparsing::is_valid_inf_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; +#endif default: return json_type::unknown; } @@ -89037,6 +95181,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/fallback/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -89052,14 +95197,11 @@ namespace simdjson { namespace fallback { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; - memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + std::memcpy(&val, chars, sizeof(uint64_t)); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -90558,6 +96700,23 @@ class value { */ simdjson_inline std::string_view raw_json_token() noexcept; + /** + * Calls the visitor for this value and everything in it, as document::visit() does for a + * whole document, for example after navigating to a field: + * + * auto error = doc["payload"].visit(visitor); + * + * The value must not have been read. The walk does not move the iterator: to go on, read the + * value or the next field or element as usual. A string with escapes is valid until you read + * the document further or visit again. The maximal depth counts from the root of the document. + * A value at the root also fails if anything follows it. + * + * @returns SUCCESS, OUT_OF_ORDER_ITERATION if the value has been read, the first error found + * in the value, or the first error the visitor returns. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); + /** * Get a string_view pointing at this value in the JSON document. * If this element is an array or an object, it consumes the array or the object @@ -90875,6 +97034,8 @@ struct simdjson_result : public fallback::implementat /** @copydoc simdjson_inline std::string_view value::raw_json_token() const noexcept */ simdjson_inline simdjson_result raw_json_token() noexcept; simdjson_inline simdjson_result raw_json() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** @copydoc simdjson_inline simdjson_result current_location() noexcept */ simdjson_inline simdjson_result current_location() noexcept; @@ -91220,6 +97381,29 @@ class json_iterator { simdjson_inline error_code out_of_place_error() noexcept; /** Tells whether the string before pos, followed by a colon, is a key. */ static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; + /** + * Validates the array or object at the current position and everything in it, without + * recursion. Outside of streaming mode, it also checks that nothing follows it. It does + * not move the iterator. + */ + simdjson_warn_unused error_code validate_container() noexcept; + static simdjson_inline bool has_backslash(const uint8_t *src, size_t len) noexcept; + /** + * Calls the visitor for the array or object at the start position and everything in it, + * without recursion (see document::visit()). The container is at depth parent_depth + 1. At + * the root (parent_depth == 0) and outside of streaming mode, it also checks that nothing + * follows it. It does not move the iterator. Escaped strings are copied into the string + * buffer. + */ + template + simdjson_warn_unused error_code visit_container(V &visitor, token_position start, size_t parent_depth); + template + simdjson_warn_unused simdjson_inline error_code visit_string(const uint8_t *quote, bool key, V &visitor); + template + simdjson_warn_unused simdjson_inline error_code visit_scalar(const uint8_t *src, V &visitor); + /** Calls the visitor for a number that numberparsing::parse_number accepted. */ + template + static simdjson_warn_unused simdjson_inline error_code visit_number(const number &value, const char *raw, V &visitor); /** * Tell whether the iterator is still at the start @@ -91409,7 +97593,8 @@ class json_iterator { /** * Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with * N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero. - * Trailing whitespace, commas, and record separators (0x1E) do not count toward max_len. + * Trailing whitespace does not count toward max_len. A comma or record + * separator (0x1E) is ignored only for a document stream. * The buffer (tmpbuf) is padded with space characters. */ simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept; @@ -92105,6 +98290,33 @@ class parser { */ simdjson_warn_unused simdjson_result iterate_raw(padded_string_view json) & noexcept; + /** + * Parses the document and walks it once with the visitor: the same as iterate() followed by + * document::visit(), with the same values and, when the visitor returns SUCCESS, the same + * error code, but faster on small documents. + * + * counting_visitor visitor; + * auto error = parser.visit(R"({"stars":[1,2,3]})"_padded, visitor); + * + * A document of at most MAX_ONE_PASS_VISIT bytes whose root is an object or an array is read in + * a single pass, without the structural index that iterate() builds. Some checks, such as the + * UTF-8 validation, then come at the end of the walk: on an invalid document, the visitor may + * have seen part or all of it before visit() returns the error code of document::visit(), and + * an error returned by the visitor may come first. With SIMDJSON_ENABLE_NAN_INF or + * SIMDJSON_ALLOW_TRAILING_COMMAS, there is no one-pass walk. + * + * See document::visit() for the methods of the visitor and the lifetime of the strings. + * + * @param json The JSON to parse, with at least SIMDJSON_PADDING bytes after it. + * @param visitor The visitor. + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(padded_string_view json, V &visitor) &; + /** Documents of at most this many bytes may be visited in one pass, see visit(). */ + static constexpr size_t MAX_ONE_PASS_VISIT = 32; + /** * Parse a buffer containing many JSON documents. @@ -92263,6 +98475,20 @@ class parser { */ simdjson_pure simdjson_inline size_t max_depth() const noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the string buffer and the structural indexes) through a buffer_allocator. + * nullptr, the default, uses new[]. The allocator must outlive the parser. + * + * Buffers that the parser already holds keep the allocator that allocated + * them until the parser grows them, so set the allocator before the first + * document or the first call to allocate(). A failed allocation makes the + * parser return MEMALLOC and leaves its buffers as they were. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + /** * Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length * and `max_depth` depth. @@ -92372,17 +98598,27 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr& get_threadlocal_parser_if_exists(); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + simdjson_inline void drop_trailing_commas(const uint8_t *buf) noexcept; +#endif #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** + * The one-pass walk of visit(). Returns UNINITIALIZED when it does not handle the document, + * and TAPE_ERROR when the document is invalid. visitor_failed tells an error of the visitor. + */ + template + simdjson_warn_unused simdjson_inline error_code visit_one_pass(const uint8_t *buf, size_t len, V &visitor, bool &visitor_failed); /** @private [for benchmarking access] The implementation to use */ std::unique_ptr implementation{}; size_t _capacity{0}; size_t _max_capacity; size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; - std::unique_ptr string_buf{}; + simdjson::internal::allocated_array string_buf{}; + const buffer_allocator *_allocator{nullptr}; #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; @@ -93640,6 +99876,58 @@ class document { * left as is. */ inline void rewind() noexcept; + /** + * Validates the whole document: its structure, every string (escapes included), every + * number, true, false and null, and that nothing follows the root value. Strings are + * checked as get_string() checks them and numbers as get_double() does. The document is + * rewound before and after, so that it can be iterated after a successful validation. + * + * It is faster than iterating through every value, because it walks the tokens directly, + * without creating values, arrays or objects. + * + * @returns SUCCESS if the document is valid, or the error found first. + */ + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + /** + * Walks the whole document once and calls the visitor for each value, in document order. + * Use it to build your own representation of the document (a tree, columns, ...) faster + * than by iterating, as the walk creates no values, arrays or objects. + * + * The visitor provides these methods. Each returns an error_code: anything but SUCCESS stops + * the walk, and visit() returns it. + * + * error_code on_object_start(); + * error_code on_object_end(uint32_t member_count); + * error_code on_array_start(); + * error_code on_array_end(uint32_t element_count); + * error_code on_key(std::string_view key); // before each member value + * error_code on_string(std::string_view value); + * error_code on_int64(int64_t value, const char *raw); // integers that fit an int64_t + * error_code on_uint64(uint64_t value, const char *raw); // larger positive integers + * error_code on_double(double value, const char *raw); + * error_code on_bool(bool value); + * error_code on_null(); + * + * raw points at the number in the document, so that the visitor can tell -0 from 0, for + * example. As with the DOM parser, an integer that does not fit in 64 bits is a BIGINT_ERROR. + * + * A key or a string without escapes is a view into the document: it is valid as long as the + * document's bytes are. A key or a string with escapes is unescaped into the parser: it is + * valid until the document is iterated or visited again, or the parser parses another + * document. + * + * visit() succeeds exactly when the DOM parser does. An error may come after the visitor has + * seen part of the document. The document is rewound before and after the walk, so that it + * can be iterated afterwards. The visitor may throw: the exception goes through visit(), and + * the document must then be rewound before it is used again. + * + * To parse and visit a document in one call, faster on small documents, see parser::visit(). + * + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** * Returns debugging information. */ @@ -93810,6 +100098,9 @@ class document { simdjson_inline value_iterator resume_value_iterator() noexcept; simdjson_inline value_iterator get_root_value_iterator() noexcept; + /** The walk of visit(), between its two rewinds. */ + template + simdjson_warn_unused simdjson_inline error_code visit_root(V &visitor); simdjson_inline simdjson_result start_or_resume_object() noexcept; static simdjson_inline document start(ondemand::json_iterator &&iter) noexcept; @@ -94029,6 +100320,9 @@ struct simdjson_result : public fallback::implemen simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); simdjson_inline simdjson_result get_array() & noexcept; simdjson_inline simdjson_result get_object() & noexcept; @@ -97316,6 +103610,7 @@ inline std::ostream& operator<<(std::ostream& out, simdjson::simdjson_result #include +#include #if SIMDJSON_STATIC_REFLECTION #include #include @@ -97525,9 +103820,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { SIMDJSON_TRY(v.get(scratch.elements.emplace_back())); release.parsed++; } - out.reserve(release.parsed); - release.complete = true; - for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + if constexpr (std::is_trivially_copyable_v) { + out.assign(scratch.elements.begin(), scratch.elements.end()); + release.complete = true; + } else if (sizeof(value_type) <= 32 && scratch.elements.capacity() / 2 < release.parsed) { + // Hand the buffer over only when it is at least half full, so that out + // does not keep the capacity of an earlier, larger array. Swapping + // large structs is slower than moving them (recipe_book benchmark). + size_t const capacity = scratch.elements.capacity(); + out.swap(scratch.elements); + release.complete = true; + if (capacity * sizeof(value_type) <= (1 << 20)) { scratch.elements.reserve(capacity); } + } else { + out.reserve(release.parsed); + release.complete = true; + for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + } return SUCCESS; } } @@ -97757,7 +104065,11 @@ consteval void append_eligible_fields(std::meta::info type, std::vector(std::meta::substitute(^^flattenable_type, {flattened}))) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member whose type is a structure deserialized member by member", mem); +#else + simdjson::detail::flatten_requires_a_member_deserialized_member_by_member(); +#endif } append_eligible_fields(flattened, prefix, fields); } else { @@ -99113,6 +105425,27 @@ simdjson_warn_unused simdjson_inline simdjson_result value::get_number() return iter.get_number(); } +template +simdjson_warn_unused simdjson_inline error_code value::visit(V &visitor) { + if (!iter.is_at_start()) { return OUT_OF_ORDER_ITERATION; } + json_iterator &json_iter = iter.json_iter(); + const uint8_t *const json = iter.peek_start(); + // The escaped strings of the value go where reading it would put them, so that the string + // buffer has room for them however many times the value is visited. + uint8_t *const string_buf_loc = json_iter._string_buf_loc; + error_code error; + switch (*json) { + case '{': case '[': + error = json_iter.visit_container(visitor, iter.start_position(), size_t(iter.depth() - 1)); + break; + // A scalar value is nested in a container: its parser reads inside the document. + case '"': error = json_iter.visit_string(json, false, visitor); break; + default: error = json_iter.visit_scalar(json, visitor); break; + } + json_iter._string_buf_loc = string_buf_loc; + return error; +} + simdjson_inline std::string_view value::raw_json_token() noexcept { return std::string_view(reinterpret_cast(iter.peek_start()), iter.peek_start_length()); } @@ -99524,6 +105857,12 @@ simdjson_inline simdjson_result::operator bool() noex } #endif +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + simdjson_inline simdjson_result simdjson_result::raw_json_token() noexcept { if (error()) { return error(); } return first.raw_json_token(); @@ -99619,6 +105958,124 @@ inline void document::rewind() noexcept { static_cast(iter.rewind()); } +simdjson_warn_unused simdjson_inline error_code document::validate() noexcept { + SIMDJSON_TRY(iter.rewind()); + const bool check_trailing = !iter.streaming(); + const uint8_t first = *iter.peek(); + error_code error; + switch (first) { + case '{': case '[': + error = iter.validate_container(); + break; + case '"': + error = get_root_value_iterator().get_root_string(check_trailing, false).error(); + break; + case 't': case 'f': + error = get_root_value_iterator().get_root_bool(check_trailing).error(); + break; + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && !null_value) { error = N_ATOM_ERROR; } +#if SIMDJSON_ENABLE_NAN_INF + if (error && !get_root_value_iterator().get_root_double(check_trailing).error()) { error = SUCCESS; } +#endif + break; + } + default: + error = get_root_value_iterator().get_root_double(check_trailing).error(); + break; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit(V &visitor) { + SIMDJSON_TRY(iter.rewind()); + const error_code error = visit_root(visitor); + // The strings of the walk stay in the buffer, but an iteration may start from its beginning. + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit_root(V &visitor) { + const bool check_trailing = !iter.streaming(); + const uint8_t *const first = iter.peek(); + const char *const raw = reinterpret_cast(first); + error_code error; + switch (*first) { + case '{': case '[': + return iter.visit_container(visitor, iter.position(), 0); + case '"': { + raw_json_string text; + error = get_root_value_iterator().get_root_raw_json_string(check_trailing).get(text); + if (!error) { return iter.visit_string(first, false, visitor); } + break; + } + case 't': case 'f': { + bool value; + error = get_root_value_iterator().get_root_bool(check_trailing).get(value); + if (!error) { return visitor.on_bool(value); } + break; + } + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && null_value) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + double value; + if (!get_root_value_iterator().get_root_double(check_trailing).get(value)) { return visitor.on_double(value, raw); } +#endif + if (!error) { error = N_ATOM_ERROR; } + break; + } + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + number value; + error = get_root_value_iterator().get_root_number(check_trailing).get(value); + if (!error) { return json_iterator::visit_number(value, raw, visitor); } + break; + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': { + double value; + error = get_root_value_iterator().get_root_double(check_trailing).get(value); + if (!error) { return visitor.on_double(value, raw); } + return error == TRAILING_CONTENT ? error : TAPE_ERROR; + } +#endif + default: + return TAPE_ERROR; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (*first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + return error; +} + inline std::string document::to_debug_string() noexcept { return iter.to_string(); } @@ -100173,6 +106630,16 @@ simdjson_inline error_code simdjson_result::rewind first.rewind(); return SUCCESS; } +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + +simdjson_warn_unused simdjson_inline error_code simdjson_result::validate() noexcept { + if (error()) { return error(); } + return first.validate(); +} simdjson_inline simdjson_result simdjson_result::begin() & noexcept { if (error()) { return error(); } return first.begin(); @@ -101243,6 +107710,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } worker->start_thread(); @@ -101496,6 +107964,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch @@ -101511,6 +107982,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -101852,6 +108326,8 @@ simdjson_inline simdjson_result simdjson_result= 8; src += 8, len -= 8) { + std::memcpy(&word, src, sizeof(word)); + word ^= BACKSLASHES; + if ((word - ONES) & ~word & HIGHS) { return true; } + } + uint64_t keep; + std::memcpy(&keep, KEEP + 8 - len, sizeof(keep)); + std::memcpy(&word, src, sizeof(word)); + word = (word ^ BACKSLASHES) | ~keep; + return ((word - ONES) & ~word & HIGHS) != 0; +} + +simdjson_warn_unused simdjson_never_inline error_code json_iterator::validate_container() noexcept { + const uint8_t *const json = token.buf; + token_position pos = token.position(); + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // One bit per depth tells whether the container at that depth is an array. Deeper than + // the fixed stack allows, the bits move to the heap. + uint64_t fixed_stack[16]{}; + std::unique_ptr heap_stack; + uint64_t *is_array = fixed_stack; + size_t depth = 0; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VALIDATE_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VALIDATE_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': goto scalar_string; + default: goto scalar; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. Its bit may then + // be at max_depth, which the stack has room for. + if (++depth >= max_depth && (pos == end || json[*pos] != c + 2)) { return DEPTH_ERROR; } + // The bits move once: the next time this depth is reached, the heap holds the current + // bits and the fixed stack holds stale ones. + if (depth == sizeof(fixed_stack) * 8 && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint64_t[max_depth / 64 + 1]()); + if (!heap_stack) { return MEMALLOC; } + std::memcpy(heap_stack.get(), fixed_stack, sizeof(fixed_stack)); + is_array = heap_stack.get(); + } + if (c == '[') { + is_array[depth / 64] |= uint64_t(1) << (depth % 64); + SIMDJSON_VALIDATE_NEXT(); + if (c == ']') { goto container_end; } + goto value; + } + is_array[depth / 64] &= ~(uint64_t(1) << (depth % 64)); + SIMDJSON_VALIDATE_NEXT(); + if (c == '}') { goto container_end; } + goto key; + +key: + if (c != '"') { return TAPE_ERROR; } + // A string is valid once stage 1 has accepted the document, unless it holds an escape. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + SIMDJSON_VALIDATE_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VALIDATE_NEXT(); + goto value; + +scalar_string: + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + goto value_end; + +scalar: + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + break; + default: + return TAPE_ERROR; + } + // The scalar is not the last token, so the parsers read inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + switch (c) { + case 't': if (!atomparsing::is_valid_true_atom(json + index)) { return T_ATOM_ERROR; } break; + case 'f': if (!atomparsing::is_valid_false_atom(json + index)) { return F_ATOM_ERROR; } break; + case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (!atomparsing::is_valid_null_atom(json + index) && !atomparsing::is_valid_nan_atom(json + index)) { return N_ATOM_ERROR; } +#else + if (!atomparsing::is_valid_null_atom(json + index)) { return N_ATOM_ERROR; } +#endif + break; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': if (!atomparsing::is_valid_nan_atom(json + index)) { return TAPE_ERROR; } break; + case 'i': case 'I': if (!atomparsing::is_valid_inf_atom(json + index)) { return TAPE_ERROR; } break; +#endif + default: + if (numberparsing::parse_double(json + index).error()) { return NUMBER_ERROR; } + break; + } + +value_end: + SIMDJSON_VALIDATE_NEXT(); + if (c == ',') { + SIMDJSON_VALIDATE_NEXT(); + if (is_array[depth / 64] & (uint64_t(1) << (depth % 64))) { goto value; } + goto key; + } + if (c != (is_array[depth / 64] & (uint64_t(1) << (depth % 64)) ? ']' : '}')) { return TAPE_ERROR; } + +container_end: + if (--depth > 0) { goto value_end; } +#undef SIMDJSON_VALIDATE_NEXT + if (!streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_number(const number &value, const char *raw, V &visitor) { + switch (value.get_number_type()) { + case number_type::signed_integer: return visitor.on_int64(value.get_int64(), raw); + case number_type::unsigned_integer: return visitor.on_uint64(value.get_uint64(), raw); + case number_type::floating_point_number: return visitor.on_double(value.get_double(), raw); + default: return BIGINT_ERROR; + } +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_string(const uint8_t *quote, bool key, V &visitor) { + const uint8_t *const start = quote + 1; + // A string without escapes is passed as it is in the document. + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (const uint8_t *src = start;; src += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(src, scratch); + if (bs_quote.has_quote_first()) { + std::string_view text(reinterpret_cast(start), size_t(src - start) + size_t(bs_quote.quote_index())); + return key ? visitor.on_key(text) : visitor.on_string(text); + } + if (bs_quote.has_backslash()) { break; } + } + uint8_t *const end = parser->implementation->parse_string(start, _string_buf_loc, false); + if (!end) { return STRING_ERROR; } + std::string_view text(reinterpret_cast(_string_buf_loc), size_t(end - _string_buf_loc)); + _string_buf_loc = end; + return key ? visitor.on_key(text) : visitor.on_string(text); +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_scalar(const uint8_t *src, V &visitor) { + switch (*src) { + case 't': return atomparsing::is_valid_true_atom(src) ? visitor.on_bool(true) : T_ATOM_ERROR; + case 'f': return atomparsing::is_valid_false_atom(src) ? visitor.on_bool(false) : F_ATOM_ERROR; + case 'n': + if (atomparsing::is_valid_null_atom(src)) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } +#endif + return N_ATOM_ERROR; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + number value; + SIMDJSON_TRY(numberparsing::parse_number(src, value)); + return visit_number(value, reinterpret_cast(src), visitor); + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } + return TAPE_ERROR; + case 'i': case 'I': + if (atomparsing::is_valid_inf_atom(src)) { return visitor.on_double(std::numeric_limits::infinity(), reinterpret_cast(src)); } + return TAPE_ERROR; +#endif + default: + return TAPE_ERROR; + } +} + +template +simdjson_warn_unused error_code json_iterator::visit_container(V &visitor, token_position start, size_t parent_depth) { + const uint8_t *const json = token.buf; + token_position pos = start; + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // For each open container, the number of its elements so far, with the top bit set for an + // array. Deeper than the fixed stack allows, the stack moves to the heap. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + constexpr size_t FIXED_DEPTH = 64; + uint32_t fixed_stack[FIXED_DEPTH]; + std::unique_ptr heap_stack; + uint32_t *stack = fixed_stack; + size_t depth = parent_depth; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VISIT_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VISIT_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': + // A string is not the last token, so that its closing quote is inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, false, visitor)); + goto value_end; + default: + // The scalar is not the last token, so the parsers read inside the document. + if (simdjson_unlikely(pos == end)) { + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + return INCOMPLETE_ARRAY_OR_OBJECT; + default: + return TAPE_ERROR; + } + } + SIMDJSON_TRY(visit_scalar(json + index, visitor)); + goto value_end; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. + if (pos != end && json[*pos] == c + 2) { + pos++; + if (c == '[') { + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_TRY(visitor.on_array_end(0)); + } else { + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_TRY(visitor.on_object_end(0)); + } + if (depth == parent_depth) { goto document_end; } + goto value_end; + } + if (++depth >= max_depth) { return DEPTH_ERROR; } + // Copy the fixed stack once. A later container at this depth must keep the + // counts already stored on the heap. + if (depth >= FIXED_DEPTH && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint32_t[max_depth]); + if (!heap_stack) { return MEMALLOC; } + // Only the slots past the parent were written. + if (parent_depth + 1 < FIXED_DEPTH) { + std::memcpy(heap_stack.get() + parent_depth + 1, fixed_stack + parent_depth + 1, (FIXED_DEPTH - parent_depth - 1) * sizeof(fixed_stack[0])); + } + stack = heap_stack.get(); + } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_VISIT_NEXT(); + goto value; + } + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_VISIT_NEXT(); + +key: + if (c != '"') { return TAPE_ERROR; } + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, true, visitor)); + SIMDJSON_VISIT_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VISIT_NEXT(); + goto value; + +value_end: + SIMDJSON_VISIT_NEXT(); + if (c == ',') { + stack[depth]++; + SIMDJSON_VISIT_NEXT(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_object_end(stack[depth])); + } + if (--depth > parent_depth) { goto value_end; } + +document_end: +#undef SIMDJSON_VISIT_NEXT + if (parent_depth == 0 && !streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + simdjson_inline bool json_iterator::at_root() const noexcept { return position() == root_position(); } @@ -102492,10 +109297,20 @@ simdjson_warn_unused simdjson_inline bool json_iterator::copy_to_buffer(const ui // peek_root_length() stops at the next structural index. Stage 1 omits the // comma or RS (0x1E) that separates stream documents, so that byte and the // whitespace around it remain in the span. RS is not a valid number finisher. + // Outside of a stream, the comma and RS are not separators: some kernels + // keep RS in the scalar token, and dropping it would accept "1\x1e". while (max_len > 0) { const uint8_t last = json[max_len - 1]; + // iterate_allow_incomplete_json() reuses _streaming, so a root scalar + // there is not a document_stream. +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + const bool separator = _streaming && !_allow_incomplete_json && + (last == ',' || last == 0x1E); +#else + const bool separator = _streaming && (last == ',' || last == 0x1E); +#endif if (last != ' ' && last != '\t' && last != '\n' && last != '\r' && - last != ',' && last != 0x1E) { + !separator) { break; } max_len--; @@ -103925,22 +110740,22 @@ simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capa return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - std::unique_ptr new_string_buf(new (std::nothrow) uint8_t[string_capacity]); - if (!new_string_buf) { return MEMALLOC; } + simdjson::internal::allocated_array new_string_buf; + if (!new_string_buf.allocate(string_capacity, _allocator)) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr new_start_positions(new (std::nothrow) token_position[new_max_depth]); if (!new_start_positions) { return MEMALLOC; } #endif - if (implementation) { - error_code err = implementation->allocate(new_capacity, new_max_depth); - if (err) { return err; } - } else { - error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, new_max_depth, implementation); if (err) { implementation.reset(); return err; } } + implementation->allocator = _allocator; + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } string_buf = std::move(new_string_buf); #if SIMDJSON_DEVELOPMENT_CHECKS start_positions = std::move(new_start_positions); @@ -103969,9 +110784,42 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iterate(p // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return document::start({ reinterpret_cast(json.data()), this }); } +// Removes from the structural indexes each comma that follows a value and +// precedes a closing bracket, so that the iterator never sees it. The entries +// past the last index (stage 1 keeps up to three there) move with the others. +#if SIMDJSON_ALLOW_TRAILING_COMMAS +simdjson_inline void parser::drop_trailing_commas(const uint8_t *buf) noexcept { + uint32_t *indexes = implementation->structural_indexes.get(); + const uint32_t n = implementation->n_structural_indexes; + uint32_t kept = 0; + uint8_t previous = '['; + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = buf[indexes[i]]; + if (c == ',' && i + 1 < n && previous != '[' && previous != '{' && previous != ',' && previous != ':') { + const uint8_t next = buf[indexes[i + 1]]; + if (next == ']' || next == '}') { + previous = c; + continue; + } + } + indexes[kept++] = indexes[i]; + previous = c; + } + if (kept != n) { + indexes[kept] = indexes[n]; + indexes[kept + 1] = indexes[n + 1]; + indexes[kept + 2] = indexes[n + 2]; + implementation->n_structural_indexes = kept; + } +} +#endif // SIMDJSON_ALLOW_TRAILING_COMMAS + #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_warn_unused simdjson_inline simdjson_result parser::iterate_allow_incomplete_json(padded_string_view json) & noexcept { if (!json.has_sufficient_padding()) { return INSUFFICIENT_PADDING; } @@ -104075,9 +110923,210 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iter // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return json_iterator(reinterpret_cast(json.data()), this); } +namespace { +struct ignoring_visitor { + simdjson_inline error_code on_object_start() { return SUCCESS; } + simdjson_inline error_code on_object_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_array_start() { return SUCCESS; } + simdjson_inline error_code on_array_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_key(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_string(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_int64(int64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_uint64(uint64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_double(double, const char *) { return SUCCESS; } + simdjson_inline error_code on_bool(bool) { return SUCCESS; } + simdjson_inline error_code on_null() { return SUCCESS; } +}; +} // unnamed namespace + +template +simdjson_warn_unused simdjson_inline error_code parser::visit(padded_string_view json, V &visitor) & { +#if !SIMDJSON_ENABLE_NAN_INF && !SIMDJSON_ALLOW_TRAILING_COMMAS + if (json.length() <= MAX_ONE_PASS_VISIT && json.has_sufficient_padding()) { + if (capacity() < json.length() || !string_buf) { + SIMDJSON_TRY( allocate(json.length(), max_depth()) ); + } + bool visitor_failed = false; + const error_code error = visit_one_pass(reinterpret_cast(json.data()), json.length(), visitor, visitor_failed); + if (error != UNINITIALIZED) { + if (error != TAPE_ERROR || visitor_failed) { return error; } + // The visitor has already seen part of the document: the regular walk only finds the + // error code, and never calls the visitor a second time. + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + ignoring_visitor ignoring; + const error_code regular_error = doc.visit(ignoring); + return regular_error ? regular_error : TAPE_ERROR; + } + } +#endif + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + return doc.visit(visitor); +} + +// A single pass over the bytes, for small documents. The root must be an array or an object, and +// the last byte that is not whitespace must be ] or }: before it, runs of whitespace, digits or +// atoms stop without a bound check. Only a closing bracket or a string may reach the end. +template +simdjson_warn_unused simdjson_inline error_code parser::visit_one_pass(const uint8_t *const buf, const size_t len, V &visitor, bool &visitor_failed) { + const auto is_whitespace = [](uint8_t c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; + if (len == 0 || len > MAX_ONE_PASS_VISIT) { return UNINITIALIZED; } + const uint8_t *p = buf; + const uint8_t *last = buf + len - 1; + while (p < last && is_whitespace(*p)) { p++; } + while (last > p && is_whitespace(*last)) { last--; } + if ((*p != '{' && *p != '[') || (*last != '}' && *last != ']')) { return UNINITIALIZED; } + const uint8_t *const end = last + 1; + uint8_t *dst = string_buf.get(); + bool non_ascii = false; + // For each open container, the number of its elements so far, with the top bit set for an + // array. Each container opens at a distinct byte before the last one, so that the depth stays + // below MAX_ONE_PASS_VISIT. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + uint32_t stack[MAX_ONE_PASS_VISIT]; + size_t depth = 0; + uint8_t c = *p; + +#define SIMDJSON_ONE_PASS_CALL(EXPR) \ + do { \ + const error_code one_pass_error = (EXPR); \ + if (simdjson_unlikely(one_pass_error != SUCCESS)) { visitor_failed = true; return one_pass_error; } \ + } while (0) +#define SIMDJSON_ONE_PASS_WHITESPACE() while (is_whitespace(*p)) { p++; } +// The string at p, which is left past the closing quote. +#define SIMDJSON_ONE_PASS_STRING(METHOD) \ + do { \ + const uint8_t *const start = ++p; \ + bool escaped = false; \ + for (;; p++) { \ + if (simdjson_unlikely(p >= end)) { return TAPE_ERROR; } \ + if (*p == '"') { break; } \ + if (*p == '\\') { \ + escaped = true; \ + p++; \ + } else if (simdjson_unlikely(*p < 0x20)) { \ + return TAPE_ERROR; \ + } else if (*p >= 0x80) { \ + non_ascii = true; \ + } \ + } \ + std::string_view text(reinterpret_cast(start), size_t(p - start)); \ + p++; \ + if (escaped) { \ + uint8_t *const unescaped_end = implementation->parse_string(start, dst, false); \ + if (unescaped_end == nullptr) { return TAPE_ERROR; } \ + text = std::string_view(reinterpret_cast(dst), size_t(unescaped_end - dst)); \ + dst = unescaped_end; \ + } \ + SIMDJSON_ONE_PASS_CALL(visitor.METHOD(text)); \ + } while (0) + + goto container_start; + +value: + switch (*p) { + case '{': case '[': + c = *p; + goto container_start; + case '"': + SIMDJSON_ONE_PASS_STRING(on_string); + goto value_end; + case 't': + if (!atomparsing::is_valid_true_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(true)); + p += 4; + goto value_end; + case 'f': + if (!atomparsing::is_valid_false_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(false)); + p += 5; + goto value_end; + case 'n': + if (!atomparsing::is_valid_null_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_null()); + p += 4; + goto value_end; + default: { + number value; + if (numberparsing::parse_number(p, value) != SUCCESS) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(json_iterator::visit_number(value, reinterpret_cast(p), visitor)); + while (jsoncharutils::is_not_structural_or_whitespace(*p)) { p++; } + goto value_end; + } + } + +container_start: + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + // As in DOM, an empty container does not count toward the maximal depth. + if (*p == c + 2) { + p++; + if (c == '[') { + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(0)); + } else { + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(0)); + } + if (depth == 0) { goto document_end; } + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + if (++depth >= max_depth()) { return TAPE_ERROR; } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + goto value; + } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + +key: + if (*p != '"') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_STRING(on_key); + SIMDJSON_ONE_PASS_WHITESPACE(); + if (*p != ':') { return TAPE_ERROR; } + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + goto value; + +value_end: + SIMDJSON_ONE_PASS_WHITESPACE(); + c = *p++; + if (c == ',') { + stack[depth]++; + SIMDJSON_ONE_PASS_WHITESPACE(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(stack[depth])); + } + if (--depth > 0) { + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + +document_end: +#undef SIMDJSON_ONE_PASS_CALL +#undef SIMDJSON_ONE_PASS_WHITESPACE +#undef SIMDJSON_ONE_PASS_STRING + if (p != end) { return TAPE_ERROR; } + if (non_ascii && !simdjson::validate_utf8(reinterpret_cast(buf), len)) { return TAPE_ERROR; } + return SUCCESS; +} + inline simdjson_result parser::iterate_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept { if(batch_size < MINIMAL_BATCH_SIZE) { batch_size = MINIMAL_BATCH_SIZE; } if((len >= 3) && (std::memcmp(buf, "\xEF\xBB\xBF", 3) == 0)) { @@ -104195,6 +111244,13 @@ simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return _max_depth; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} + simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept { if(max_capacity > dom::MINIMAL_DOCUMENT_CAPACITY) { _max_capacity = max_capacity; @@ -104714,13 +111770,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_objec _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing } at end"); } - // If the last character is } *and* the first gibberish character is also '}' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is } *and* the first gibberish character is '}', ']' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == '}') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed object. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -105124,13 +112182,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_array _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing ] at end"); } - // If the last character is ] *and* the first gibberish character is also ']' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is ] *and* the first gibberish character is ']', '}' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == ']') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed array. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -105300,7 +112360,7 @@ simdjson_inline simdjson_result value_iterator::get_root_ // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -105324,7 +112384,7 @@ simdjson_inline simdjson_result value_iterator::get_root_number(bool che // number: -0.e-308. // NOTE: the current approach doesn't work for very big integer numbers containing more than 1074 digits. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -105406,7 +112466,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::g simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer tmpbuf[20+1] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+1)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 20 characters"); @@ -105423,7 +112483,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::ge simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64_in_string(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer tmpbuf[20+2] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+2)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 22 characters"); @@ -105444,7 +112504,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -105466,7 +112526,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -105488,7 +112548,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ // digits that matter is smaller for binary32, but the JSON document may still // spell out a long number that we must parse (and round) faithfully. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -105507,7 +112567,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ auto max_len = peek_root_length(); auto json = peek_root_scalar("float"); // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -105845,6 +112905,9 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '"': return json_type::string; case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } +#endif return json_type::null; case 't': case 'f': return json_type::boolean; @@ -105852,6 +112915,14 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return json_type::number; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; + case 'I': case 'i': + if (atomparsing::is_valid_inf_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; +#endif default: return json_type::unknown; } @@ -107115,6 +114186,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/haswell/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/haswell/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -107337,6 +114409,26 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + const __m128i lo = n >= 16 ? _mm_loadu_si128(reinterpret_cast(ptr)) : load_partial_16(ptr, n, begin, fill); + const __m128i hi = n > 16 ? load_partial_16(ptr + 16, n - 16, begin, fill) : _mm_set1_epi8(char(fill)); + return _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -108973,6 +116065,23 @@ class value { */ simdjson_inline std::string_view raw_json_token() noexcept; + /** + * Calls the visitor for this value and everything in it, as document::visit() does for a + * whole document, for example after navigating to a field: + * + * auto error = doc["payload"].visit(visitor); + * + * The value must not have been read. The walk does not move the iterator: to go on, read the + * value or the next field or element as usual. A string with escapes is valid until you read + * the document further or visit again. The maximal depth counts from the root of the document. + * A value at the root also fails if anything follows it. + * + * @returns SUCCESS, OUT_OF_ORDER_ITERATION if the value has been read, the first error found + * in the value, or the first error the visitor returns. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); + /** * Get a string_view pointing at this value in the JSON document. * If this element is an array or an object, it consumes the array or the object @@ -109290,6 +116399,8 @@ struct simdjson_result : public haswell::implementatio /** @copydoc simdjson_inline std::string_view value::raw_json_token() const noexcept */ simdjson_inline simdjson_result raw_json_token() noexcept; simdjson_inline simdjson_result raw_json() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** @copydoc simdjson_inline simdjson_result current_location() noexcept */ simdjson_inline simdjson_result current_location() noexcept; @@ -109635,6 +116746,29 @@ class json_iterator { simdjson_inline error_code out_of_place_error() noexcept; /** Tells whether the string before pos, followed by a colon, is a key. */ static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; + /** + * Validates the array or object at the current position and everything in it, without + * recursion. Outside of streaming mode, it also checks that nothing follows it. It does + * not move the iterator. + */ + simdjson_warn_unused error_code validate_container() noexcept; + static simdjson_inline bool has_backslash(const uint8_t *src, size_t len) noexcept; + /** + * Calls the visitor for the array or object at the start position and everything in it, + * without recursion (see document::visit()). The container is at depth parent_depth + 1. At + * the root (parent_depth == 0) and outside of streaming mode, it also checks that nothing + * follows it. It does not move the iterator. Escaped strings are copied into the string + * buffer. + */ + template + simdjson_warn_unused error_code visit_container(V &visitor, token_position start, size_t parent_depth); + template + simdjson_warn_unused simdjson_inline error_code visit_string(const uint8_t *quote, bool key, V &visitor); + template + simdjson_warn_unused simdjson_inline error_code visit_scalar(const uint8_t *src, V &visitor); + /** Calls the visitor for a number that numberparsing::parse_number accepted. */ + template + static simdjson_warn_unused simdjson_inline error_code visit_number(const number &value, const char *raw, V &visitor); /** * Tell whether the iterator is still at the start @@ -109824,7 +116958,8 @@ class json_iterator { /** * Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with * N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero. - * Trailing whitespace, commas, and record separators (0x1E) do not count toward max_len. + * Trailing whitespace does not count toward max_len. A comma or record + * separator (0x1E) is ignored only for a document stream. * The buffer (tmpbuf) is padded with space characters. */ simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept; @@ -110520,6 +117655,33 @@ class parser { */ simdjson_warn_unused simdjson_result iterate_raw(padded_string_view json) & noexcept; + /** + * Parses the document and walks it once with the visitor: the same as iterate() followed by + * document::visit(), with the same values and, when the visitor returns SUCCESS, the same + * error code, but faster on small documents. + * + * counting_visitor visitor; + * auto error = parser.visit(R"({"stars":[1,2,3]})"_padded, visitor); + * + * A document of at most MAX_ONE_PASS_VISIT bytes whose root is an object or an array is read in + * a single pass, without the structural index that iterate() builds. Some checks, such as the + * UTF-8 validation, then come at the end of the walk: on an invalid document, the visitor may + * have seen part or all of it before visit() returns the error code of document::visit(), and + * an error returned by the visitor may come first. With SIMDJSON_ENABLE_NAN_INF or + * SIMDJSON_ALLOW_TRAILING_COMMAS, there is no one-pass walk. + * + * See document::visit() for the methods of the visitor and the lifetime of the strings. + * + * @param json The JSON to parse, with at least SIMDJSON_PADDING bytes after it. + * @param visitor The visitor. + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(padded_string_view json, V &visitor) &; + /** Documents of at most this many bytes may be visited in one pass, see visit(). */ + static constexpr size_t MAX_ONE_PASS_VISIT = 32; + /** * Parse a buffer containing many JSON documents. @@ -110678,6 +117840,20 @@ class parser { */ simdjson_pure simdjson_inline size_t max_depth() const noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the string buffer and the structural indexes) through a buffer_allocator. + * nullptr, the default, uses new[]. The allocator must outlive the parser. + * + * Buffers that the parser already holds keep the allocator that allocated + * them until the parser grows them, so set the allocator before the first + * document or the first call to allocate(). A failed allocation makes the + * parser return MEMALLOC and leaves its buffers as they were. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + /** * Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length * and `max_depth` depth. @@ -110787,17 +117963,27 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr& get_threadlocal_parser_if_exists(); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + simdjson_inline void drop_trailing_commas(const uint8_t *buf) noexcept; +#endif #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** + * The one-pass walk of visit(). Returns UNINITIALIZED when it does not handle the document, + * and TAPE_ERROR when the document is invalid. visitor_failed tells an error of the visitor. + */ + template + simdjson_warn_unused simdjson_inline error_code visit_one_pass(const uint8_t *buf, size_t len, V &visitor, bool &visitor_failed); /** @private [for benchmarking access] The implementation to use */ std::unique_ptr implementation{}; size_t _capacity{0}; size_t _max_capacity; size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; - std::unique_ptr string_buf{}; + simdjson::internal::allocated_array string_buf{}; + const buffer_allocator *_allocator{nullptr}; #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; @@ -112055,6 +119241,58 @@ class document { * left as is. */ inline void rewind() noexcept; + /** + * Validates the whole document: its structure, every string (escapes included), every + * number, true, false and null, and that nothing follows the root value. Strings are + * checked as get_string() checks them and numbers as get_double() does. The document is + * rewound before and after, so that it can be iterated after a successful validation. + * + * It is faster than iterating through every value, because it walks the tokens directly, + * without creating values, arrays or objects. + * + * @returns SUCCESS if the document is valid, or the error found first. + */ + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + /** + * Walks the whole document once and calls the visitor for each value, in document order. + * Use it to build your own representation of the document (a tree, columns, ...) faster + * than by iterating, as the walk creates no values, arrays or objects. + * + * The visitor provides these methods. Each returns an error_code: anything but SUCCESS stops + * the walk, and visit() returns it. + * + * error_code on_object_start(); + * error_code on_object_end(uint32_t member_count); + * error_code on_array_start(); + * error_code on_array_end(uint32_t element_count); + * error_code on_key(std::string_view key); // before each member value + * error_code on_string(std::string_view value); + * error_code on_int64(int64_t value, const char *raw); // integers that fit an int64_t + * error_code on_uint64(uint64_t value, const char *raw); // larger positive integers + * error_code on_double(double value, const char *raw); + * error_code on_bool(bool value); + * error_code on_null(); + * + * raw points at the number in the document, so that the visitor can tell -0 from 0, for + * example. As with the DOM parser, an integer that does not fit in 64 bits is a BIGINT_ERROR. + * + * A key or a string without escapes is a view into the document: it is valid as long as the + * document's bytes are. A key or a string with escapes is unescaped into the parser: it is + * valid until the document is iterated or visited again, or the parser parses another + * document. + * + * visit() succeeds exactly when the DOM parser does. An error may come after the visitor has + * seen part of the document. The document is rewound before and after the walk, so that it + * can be iterated afterwards. The visitor may throw: the exception goes through visit(), and + * the document must then be rewound before it is used again. + * + * To parse and visit a document in one call, faster on small documents, see parser::visit(). + * + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** * Returns debugging information. */ @@ -112225,6 +119463,9 @@ class document { simdjson_inline value_iterator resume_value_iterator() noexcept; simdjson_inline value_iterator get_root_value_iterator() noexcept; + /** The walk of visit(), between its two rewinds. */ + template + simdjson_warn_unused simdjson_inline error_code visit_root(V &visitor); simdjson_inline simdjson_result start_or_resume_object() noexcept; static simdjson_inline document start(ondemand::json_iterator &&iter) noexcept; @@ -112444,6 +119685,9 @@ struct simdjson_result : public haswell::implementa simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); simdjson_inline simdjson_result get_array() & noexcept; simdjson_inline simdjson_result get_object() & noexcept; @@ -115731,6 +122975,7 @@ inline std::ostream& operator<<(std::ostream& out, simdjson::simdjson_result #include +#include #if SIMDJSON_STATIC_REFLECTION #include #include @@ -115940,9 +123185,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { SIMDJSON_TRY(v.get(scratch.elements.emplace_back())); release.parsed++; } - out.reserve(release.parsed); - release.complete = true; - for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + if constexpr (std::is_trivially_copyable_v) { + out.assign(scratch.elements.begin(), scratch.elements.end()); + release.complete = true; + } else if (sizeof(value_type) <= 32 && scratch.elements.capacity() / 2 < release.parsed) { + // Hand the buffer over only when it is at least half full, so that out + // does not keep the capacity of an earlier, larger array. Swapping + // large structs is slower than moving them (recipe_book benchmark). + size_t const capacity = scratch.elements.capacity(); + out.swap(scratch.elements); + release.complete = true; + if (capacity * sizeof(value_type) <= (1 << 20)) { scratch.elements.reserve(capacity); } + } else { + out.reserve(release.parsed); + release.complete = true; + for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + } return SUCCESS; } } @@ -116172,7 +123430,11 @@ consteval void append_eligible_fields(std::meta::info type, std::vector(std::meta::substitute(^^flattenable_type, {flattened}))) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member whose type is a structure deserialized member by member", mem); +#else + simdjson::detail::flatten_requires_a_member_deserialized_member_by_member(); +#endif } append_eligible_fields(flattened, prefix, fields); } else { @@ -117528,6 +124790,27 @@ simdjson_warn_unused simdjson_inline simdjson_result value::get_number() return iter.get_number(); } +template +simdjson_warn_unused simdjson_inline error_code value::visit(V &visitor) { + if (!iter.is_at_start()) { return OUT_OF_ORDER_ITERATION; } + json_iterator &json_iter = iter.json_iter(); + const uint8_t *const json = iter.peek_start(); + // The escaped strings of the value go where reading it would put them, so that the string + // buffer has room for them however many times the value is visited. + uint8_t *const string_buf_loc = json_iter._string_buf_loc; + error_code error; + switch (*json) { + case '{': case '[': + error = json_iter.visit_container(visitor, iter.start_position(), size_t(iter.depth() - 1)); + break; + // A scalar value is nested in a container: its parser reads inside the document. + case '"': error = json_iter.visit_string(json, false, visitor); break; + default: error = json_iter.visit_scalar(json, visitor); break; + } + json_iter._string_buf_loc = string_buf_loc; + return error; +} + simdjson_inline std::string_view value::raw_json_token() noexcept { return std::string_view(reinterpret_cast(iter.peek_start()), iter.peek_start_length()); } @@ -117939,6 +125222,12 @@ simdjson_inline simdjson_result::operator bool() noexc } #endif +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + simdjson_inline simdjson_result simdjson_result::raw_json_token() noexcept { if (error()) { return error(); } return first.raw_json_token(); @@ -118034,6 +125323,124 @@ inline void document::rewind() noexcept { static_cast(iter.rewind()); } +simdjson_warn_unused simdjson_inline error_code document::validate() noexcept { + SIMDJSON_TRY(iter.rewind()); + const bool check_trailing = !iter.streaming(); + const uint8_t first = *iter.peek(); + error_code error; + switch (first) { + case '{': case '[': + error = iter.validate_container(); + break; + case '"': + error = get_root_value_iterator().get_root_string(check_trailing, false).error(); + break; + case 't': case 'f': + error = get_root_value_iterator().get_root_bool(check_trailing).error(); + break; + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && !null_value) { error = N_ATOM_ERROR; } +#if SIMDJSON_ENABLE_NAN_INF + if (error && !get_root_value_iterator().get_root_double(check_trailing).error()) { error = SUCCESS; } +#endif + break; + } + default: + error = get_root_value_iterator().get_root_double(check_trailing).error(); + break; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit(V &visitor) { + SIMDJSON_TRY(iter.rewind()); + const error_code error = visit_root(visitor); + // The strings of the walk stay in the buffer, but an iteration may start from its beginning. + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit_root(V &visitor) { + const bool check_trailing = !iter.streaming(); + const uint8_t *const first = iter.peek(); + const char *const raw = reinterpret_cast(first); + error_code error; + switch (*first) { + case '{': case '[': + return iter.visit_container(visitor, iter.position(), 0); + case '"': { + raw_json_string text; + error = get_root_value_iterator().get_root_raw_json_string(check_trailing).get(text); + if (!error) { return iter.visit_string(first, false, visitor); } + break; + } + case 't': case 'f': { + bool value; + error = get_root_value_iterator().get_root_bool(check_trailing).get(value); + if (!error) { return visitor.on_bool(value); } + break; + } + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && null_value) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + double value; + if (!get_root_value_iterator().get_root_double(check_trailing).get(value)) { return visitor.on_double(value, raw); } +#endif + if (!error) { error = N_ATOM_ERROR; } + break; + } + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + number value; + error = get_root_value_iterator().get_root_number(check_trailing).get(value); + if (!error) { return json_iterator::visit_number(value, raw, visitor); } + break; + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': { + double value; + error = get_root_value_iterator().get_root_double(check_trailing).get(value); + if (!error) { return visitor.on_double(value, raw); } + return error == TRAILING_CONTENT ? error : TAPE_ERROR; + } +#endif + default: + return TAPE_ERROR; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (*first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + return error; +} + inline std::string document::to_debug_string() noexcept { return iter.to_string(); } @@ -118588,6 +125995,16 @@ simdjson_inline error_code simdjson_result::rewind( first.rewind(); return SUCCESS; } +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + +simdjson_warn_unused simdjson_inline error_code simdjson_result::validate() noexcept { + if (error()) { return error(); } + return first.validate(); +} simdjson_inline simdjson_result simdjson_result::begin() & noexcept { if (error()) { return error(); } return first.begin(); @@ -119658,6 +127075,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } worker->start_thread(); @@ -119911,6 +127329,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch @@ -119926,6 +127347,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -120267,6 +127691,8 @@ simdjson_inline simdjson_result simdjson_result= 8; src += 8, len -= 8) { + std::memcpy(&word, src, sizeof(word)); + word ^= BACKSLASHES; + if ((word - ONES) & ~word & HIGHS) { return true; } + } + uint64_t keep; + std::memcpy(&keep, KEEP + 8 - len, sizeof(keep)); + std::memcpy(&word, src, sizeof(word)); + word = (word ^ BACKSLASHES) | ~keep; + return ((word - ONES) & ~word & HIGHS) != 0; +} + +simdjson_warn_unused simdjson_never_inline error_code json_iterator::validate_container() noexcept { + const uint8_t *const json = token.buf; + token_position pos = token.position(); + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // One bit per depth tells whether the container at that depth is an array. Deeper than + // the fixed stack allows, the bits move to the heap. + uint64_t fixed_stack[16]{}; + std::unique_ptr heap_stack; + uint64_t *is_array = fixed_stack; + size_t depth = 0; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VALIDATE_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VALIDATE_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': goto scalar_string; + default: goto scalar; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. Its bit may then + // be at max_depth, which the stack has room for. + if (++depth >= max_depth && (pos == end || json[*pos] != c + 2)) { return DEPTH_ERROR; } + // The bits move once: the next time this depth is reached, the heap holds the current + // bits and the fixed stack holds stale ones. + if (depth == sizeof(fixed_stack) * 8 && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint64_t[max_depth / 64 + 1]()); + if (!heap_stack) { return MEMALLOC; } + std::memcpy(heap_stack.get(), fixed_stack, sizeof(fixed_stack)); + is_array = heap_stack.get(); + } + if (c == '[') { + is_array[depth / 64] |= uint64_t(1) << (depth % 64); + SIMDJSON_VALIDATE_NEXT(); + if (c == ']') { goto container_end; } + goto value; + } + is_array[depth / 64] &= ~(uint64_t(1) << (depth % 64)); + SIMDJSON_VALIDATE_NEXT(); + if (c == '}') { goto container_end; } + goto key; + +key: + if (c != '"') { return TAPE_ERROR; } + // A string is valid once stage 1 has accepted the document, unless it holds an escape. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + SIMDJSON_VALIDATE_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VALIDATE_NEXT(); + goto value; + +scalar_string: + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + goto value_end; + +scalar: + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + break; + default: + return TAPE_ERROR; + } + // The scalar is not the last token, so the parsers read inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + switch (c) { + case 't': if (!atomparsing::is_valid_true_atom(json + index)) { return T_ATOM_ERROR; } break; + case 'f': if (!atomparsing::is_valid_false_atom(json + index)) { return F_ATOM_ERROR; } break; + case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (!atomparsing::is_valid_null_atom(json + index) && !atomparsing::is_valid_nan_atom(json + index)) { return N_ATOM_ERROR; } +#else + if (!atomparsing::is_valid_null_atom(json + index)) { return N_ATOM_ERROR; } +#endif + break; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': if (!atomparsing::is_valid_nan_atom(json + index)) { return TAPE_ERROR; } break; + case 'i': case 'I': if (!atomparsing::is_valid_inf_atom(json + index)) { return TAPE_ERROR; } break; +#endif + default: + if (numberparsing::parse_double(json + index).error()) { return NUMBER_ERROR; } + break; + } + +value_end: + SIMDJSON_VALIDATE_NEXT(); + if (c == ',') { + SIMDJSON_VALIDATE_NEXT(); + if (is_array[depth / 64] & (uint64_t(1) << (depth % 64))) { goto value; } + goto key; + } + if (c != (is_array[depth / 64] & (uint64_t(1) << (depth % 64)) ? ']' : '}')) { return TAPE_ERROR; } + +container_end: + if (--depth > 0) { goto value_end; } +#undef SIMDJSON_VALIDATE_NEXT + if (!streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_number(const number &value, const char *raw, V &visitor) { + switch (value.get_number_type()) { + case number_type::signed_integer: return visitor.on_int64(value.get_int64(), raw); + case number_type::unsigned_integer: return visitor.on_uint64(value.get_uint64(), raw); + case number_type::floating_point_number: return visitor.on_double(value.get_double(), raw); + default: return BIGINT_ERROR; + } +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_string(const uint8_t *quote, bool key, V &visitor) { + const uint8_t *const start = quote + 1; + // A string without escapes is passed as it is in the document. + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (const uint8_t *src = start;; src += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(src, scratch); + if (bs_quote.has_quote_first()) { + std::string_view text(reinterpret_cast(start), size_t(src - start) + size_t(bs_quote.quote_index())); + return key ? visitor.on_key(text) : visitor.on_string(text); + } + if (bs_quote.has_backslash()) { break; } + } + uint8_t *const end = parser->implementation->parse_string(start, _string_buf_loc, false); + if (!end) { return STRING_ERROR; } + std::string_view text(reinterpret_cast(_string_buf_loc), size_t(end - _string_buf_loc)); + _string_buf_loc = end; + return key ? visitor.on_key(text) : visitor.on_string(text); +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_scalar(const uint8_t *src, V &visitor) { + switch (*src) { + case 't': return atomparsing::is_valid_true_atom(src) ? visitor.on_bool(true) : T_ATOM_ERROR; + case 'f': return atomparsing::is_valid_false_atom(src) ? visitor.on_bool(false) : F_ATOM_ERROR; + case 'n': + if (atomparsing::is_valid_null_atom(src)) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } +#endif + return N_ATOM_ERROR; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + number value; + SIMDJSON_TRY(numberparsing::parse_number(src, value)); + return visit_number(value, reinterpret_cast(src), visitor); + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } + return TAPE_ERROR; + case 'i': case 'I': + if (atomparsing::is_valid_inf_atom(src)) { return visitor.on_double(std::numeric_limits::infinity(), reinterpret_cast(src)); } + return TAPE_ERROR; +#endif + default: + return TAPE_ERROR; + } +} + +template +simdjson_warn_unused error_code json_iterator::visit_container(V &visitor, token_position start, size_t parent_depth) { + const uint8_t *const json = token.buf; + token_position pos = start; + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // For each open container, the number of its elements so far, with the top bit set for an + // array. Deeper than the fixed stack allows, the stack moves to the heap. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + constexpr size_t FIXED_DEPTH = 64; + uint32_t fixed_stack[FIXED_DEPTH]; + std::unique_ptr heap_stack; + uint32_t *stack = fixed_stack; + size_t depth = parent_depth; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VISIT_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VISIT_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': + // A string is not the last token, so that its closing quote is inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, false, visitor)); + goto value_end; + default: + // The scalar is not the last token, so the parsers read inside the document. + if (simdjson_unlikely(pos == end)) { + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + return INCOMPLETE_ARRAY_OR_OBJECT; + default: + return TAPE_ERROR; + } + } + SIMDJSON_TRY(visit_scalar(json + index, visitor)); + goto value_end; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. + if (pos != end && json[*pos] == c + 2) { + pos++; + if (c == '[') { + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_TRY(visitor.on_array_end(0)); + } else { + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_TRY(visitor.on_object_end(0)); + } + if (depth == parent_depth) { goto document_end; } + goto value_end; + } + if (++depth >= max_depth) { return DEPTH_ERROR; } + // Copy the fixed stack once. A later container at this depth must keep the + // counts already stored on the heap. + if (depth >= FIXED_DEPTH && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint32_t[max_depth]); + if (!heap_stack) { return MEMALLOC; } + // Only the slots past the parent were written. + if (parent_depth + 1 < FIXED_DEPTH) { + std::memcpy(heap_stack.get() + parent_depth + 1, fixed_stack + parent_depth + 1, (FIXED_DEPTH - parent_depth - 1) * sizeof(fixed_stack[0])); + } + stack = heap_stack.get(); + } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_VISIT_NEXT(); + goto value; + } + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_VISIT_NEXT(); + +key: + if (c != '"') { return TAPE_ERROR; } + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, true, visitor)); + SIMDJSON_VISIT_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VISIT_NEXT(); + goto value; + +value_end: + SIMDJSON_VISIT_NEXT(); + if (c == ',') { + stack[depth]++; + SIMDJSON_VISIT_NEXT(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_object_end(stack[depth])); + } + if (--depth > parent_depth) { goto value_end; } + +document_end: +#undef SIMDJSON_VISIT_NEXT + if (parent_depth == 0 && !streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + simdjson_inline bool json_iterator::at_root() const noexcept { return position() == root_position(); } @@ -120907,10 +128662,20 @@ simdjson_warn_unused simdjson_inline bool json_iterator::copy_to_buffer(const ui // peek_root_length() stops at the next structural index. Stage 1 omits the // comma or RS (0x1E) that separates stream documents, so that byte and the // whitespace around it remain in the span. RS is not a valid number finisher. + // Outside of a stream, the comma and RS are not separators: some kernels + // keep RS in the scalar token, and dropping it would accept "1\x1e". while (max_len > 0) { const uint8_t last = json[max_len - 1]; + // iterate_allow_incomplete_json() reuses _streaming, so a root scalar + // there is not a document_stream. +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + const bool separator = _streaming && !_allow_incomplete_json && + (last == ',' || last == 0x1E); +#else + const bool separator = _streaming && (last == ',' || last == 0x1E); +#endif if (last != ' ' && last != '\t' && last != '\n' && last != '\r' && - last != ',' && last != 0x1E) { + !separator) { break; } max_len--; @@ -122340,22 +130105,22 @@ simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capa return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - std::unique_ptr new_string_buf(new (std::nothrow) uint8_t[string_capacity]); - if (!new_string_buf) { return MEMALLOC; } + simdjson::internal::allocated_array new_string_buf; + if (!new_string_buf.allocate(string_capacity, _allocator)) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr new_start_positions(new (std::nothrow) token_position[new_max_depth]); if (!new_start_positions) { return MEMALLOC; } #endif - if (implementation) { - error_code err = implementation->allocate(new_capacity, new_max_depth); - if (err) { return err; } - } else { - error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, new_max_depth, implementation); if (err) { implementation.reset(); return err; } } + implementation->allocator = _allocator; + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } string_buf = std::move(new_string_buf); #if SIMDJSON_DEVELOPMENT_CHECKS start_positions = std::move(new_start_positions); @@ -122384,9 +130149,42 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iterate(p // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return document::start({ reinterpret_cast(json.data()), this }); } +// Removes from the structural indexes each comma that follows a value and +// precedes a closing bracket, so that the iterator never sees it. The entries +// past the last index (stage 1 keeps up to three there) move with the others. +#if SIMDJSON_ALLOW_TRAILING_COMMAS +simdjson_inline void parser::drop_trailing_commas(const uint8_t *buf) noexcept { + uint32_t *indexes = implementation->structural_indexes.get(); + const uint32_t n = implementation->n_structural_indexes; + uint32_t kept = 0; + uint8_t previous = '['; + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = buf[indexes[i]]; + if (c == ',' && i + 1 < n && previous != '[' && previous != '{' && previous != ',' && previous != ':') { + const uint8_t next = buf[indexes[i + 1]]; + if (next == ']' || next == '}') { + previous = c; + continue; + } + } + indexes[kept++] = indexes[i]; + previous = c; + } + if (kept != n) { + indexes[kept] = indexes[n]; + indexes[kept + 1] = indexes[n + 1]; + indexes[kept + 2] = indexes[n + 2]; + implementation->n_structural_indexes = kept; + } +} +#endif // SIMDJSON_ALLOW_TRAILING_COMMAS + #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_warn_unused simdjson_inline simdjson_result parser::iterate_allow_incomplete_json(padded_string_view json) & noexcept { if (!json.has_sufficient_padding()) { return INSUFFICIENT_PADDING; } @@ -122490,9 +130288,210 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iter // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return json_iterator(reinterpret_cast(json.data()), this); } +namespace { +struct ignoring_visitor { + simdjson_inline error_code on_object_start() { return SUCCESS; } + simdjson_inline error_code on_object_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_array_start() { return SUCCESS; } + simdjson_inline error_code on_array_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_key(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_string(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_int64(int64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_uint64(uint64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_double(double, const char *) { return SUCCESS; } + simdjson_inline error_code on_bool(bool) { return SUCCESS; } + simdjson_inline error_code on_null() { return SUCCESS; } +}; +} // unnamed namespace + +template +simdjson_warn_unused simdjson_inline error_code parser::visit(padded_string_view json, V &visitor) & { +#if !SIMDJSON_ENABLE_NAN_INF && !SIMDJSON_ALLOW_TRAILING_COMMAS + if (json.length() <= MAX_ONE_PASS_VISIT && json.has_sufficient_padding()) { + if (capacity() < json.length() || !string_buf) { + SIMDJSON_TRY( allocate(json.length(), max_depth()) ); + } + bool visitor_failed = false; + const error_code error = visit_one_pass(reinterpret_cast(json.data()), json.length(), visitor, visitor_failed); + if (error != UNINITIALIZED) { + if (error != TAPE_ERROR || visitor_failed) { return error; } + // The visitor has already seen part of the document: the regular walk only finds the + // error code, and never calls the visitor a second time. + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + ignoring_visitor ignoring; + const error_code regular_error = doc.visit(ignoring); + return regular_error ? regular_error : TAPE_ERROR; + } + } +#endif + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + return doc.visit(visitor); +} + +// A single pass over the bytes, for small documents. The root must be an array or an object, and +// the last byte that is not whitespace must be ] or }: before it, runs of whitespace, digits or +// atoms stop without a bound check. Only a closing bracket or a string may reach the end. +template +simdjson_warn_unused simdjson_inline error_code parser::visit_one_pass(const uint8_t *const buf, const size_t len, V &visitor, bool &visitor_failed) { + const auto is_whitespace = [](uint8_t c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; + if (len == 0 || len > MAX_ONE_PASS_VISIT) { return UNINITIALIZED; } + const uint8_t *p = buf; + const uint8_t *last = buf + len - 1; + while (p < last && is_whitespace(*p)) { p++; } + while (last > p && is_whitespace(*last)) { last--; } + if ((*p != '{' && *p != '[') || (*last != '}' && *last != ']')) { return UNINITIALIZED; } + const uint8_t *const end = last + 1; + uint8_t *dst = string_buf.get(); + bool non_ascii = false; + // For each open container, the number of its elements so far, with the top bit set for an + // array. Each container opens at a distinct byte before the last one, so that the depth stays + // below MAX_ONE_PASS_VISIT. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + uint32_t stack[MAX_ONE_PASS_VISIT]; + size_t depth = 0; + uint8_t c = *p; + +#define SIMDJSON_ONE_PASS_CALL(EXPR) \ + do { \ + const error_code one_pass_error = (EXPR); \ + if (simdjson_unlikely(one_pass_error != SUCCESS)) { visitor_failed = true; return one_pass_error; } \ + } while (0) +#define SIMDJSON_ONE_PASS_WHITESPACE() while (is_whitespace(*p)) { p++; } +// The string at p, which is left past the closing quote. +#define SIMDJSON_ONE_PASS_STRING(METHOD) \ + do { \ + const uint8_t *const start = ++p; \ + bool escaped = false; \ + for (;; p++) { \ + if (simdjson_unlikely(p >= end)) { return TAPE_ERROR; } \ + if (*p == '"') { break; } \ + if (*p == '\\') { \ + escaped = true; \ + p++; \ + } else if (simdjson_unlikely(*p < 0x20)) { \ + return TAPE_ERROR; \ + } else if (*p >= 0x80) { \ + non_ascii = true; \ + } \ + } \ + std::string_view text(reinterpret_cast(start), size_t(p - start)); \ + p++; \ + if (escaped) { \ + uint8_t *const unescaped_end = implementation->parse_string(start, dst, false); \ + if (unescaped_end == nullptr) { return TAPE_ERROR; } \ + text = std::string_view(reinterpret_cast(dst), size_t(unescaped_end - dst)); \ + dst = unescaped_end; \ + } \ + SIMDJSON_ONE_PASS_CALL(visitor.METHOD(text)); \ + } while (0) + + goto container_start; + +value: + switch (*p) { + case '{': case '[': + c = *p; + goto container_start; + case '"': + SIMDJSON_ONE_PASS_STRING(on_string); + goto value_end; + case 't': + if (!atomparsing::is_valid_true_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(true)); + p += 4; + goto value_end; + case 'f': + if (!atomparsing::is_valid_false_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(false)); + p += 5; + goto value_end; + case 'n': + if (!atomparsing::is_valid_null_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_null()); + p += 4; + goto value_end; + default: { + number value; + if (numberparsing::parse_number(p, value) != SUCCESS) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(json_iterator::visit_number(value, reinterpret_cast(p), visitor)); + while (jsoncharutils::is_not_structural_or_whitespace(*p)) { p++; } + goto value_end; + } + } + +container_start: + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + // As in DOM, an empty container does not count toward the maximal depth. + if (*p == c + 2) { + p++; + if (c == '[') { + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(0)); + } else { + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(0)); + } + if (depth == 0) { goto document_end; } + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + if (++depth >= max_depth()) { return TAPE_ERROR; } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + goto value; + } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + +key: + if (*p != '"') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_STRING(on_key); + SIMDJSON_ONE_PASS_WHITESPACE(); + if (*p != ':') { return TAPE_ERROR; } + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + goto value; + +value_end: + SIMDJSON_ONE_PASS_WHITESPACE(); + c = *p++; + if (c == ',') { + stack[depth]++; + SIMDJSON_ONE_PASS_WHITESPACE(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(stack[depth])); + } + if (--depth > 0) { + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + +document_end: +#undef SIMDJSON_ONE_PASS_CALL +#undef SIMDJSON_ONE_PASS_WHITESPACE +#undef SIMDJSON_ONE_PASS_STRING + if (p != end) { return TAPE_ERROR; } + if (non_ascii && !simdjson::validate_utf8(reinterpret_cast(buf), len)) { return TAPE_ERROR; } + return SUCCESS; +} + inline simdjson_result parser::iterate_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept { if(batch_size < MINIMAL_BATCH_SIZE) { batch_size = MINIMAL_BATCH_SIZE; } if((len >= 3) && (std::memcmp(buf, "\xEF\xBB\xBF", 3) == 0)) { @@ -122610,6 +130609,13 @@ simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return _max_depth; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} + simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept { if(max_capacity > dom::MINIMAL_DOCUMENT_CAPACITY) { _max_capacity = max_capacity; @@ -123129,13 +131135,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_objec _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing } at end"); } - // If the last character is } *and* the first gibberish character is also '}' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is } *and* the first gibberish character is '}', ']' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == '}') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed object. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -123539,13 +131547,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_array _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing ] at end"); } - // If the last character is ] *and* the first gibberish character is also ']' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is ] *and* the first gibberish character is ']', '}' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == ']') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed array. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -123715,7 +131725,7 @@ simdjson_inline simdjson_result value_iterator::get_root_n // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -123739,7 +131749,7 @@ simdjson_inline simdjson_result value_iterator::get_root_number(bool che // number: -0.e-308. // NOTE: the current approach doesn't work for very big integer numbers containing more than 1074 digits. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -123821,7 +131831,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::g simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer tmpbuf[20+1] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+1)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 20 characters"); @@ -123838,7 +131848,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::ge simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64_in_string(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer tmpbuf[20+2] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+2)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 22 characters"); @@ -123859,7 +131869,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -123881,7 +131891,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -123903,7 +131913,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ // digits that matter is smaller for binary32, but the JSON document may still // spell out a long number that we must parse (and round) faithfully. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -123922,7 +131932,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ auto max_len = peek_root_length(); auto json = peek_root_scalar("float"); // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -124260,6 +132270,9 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '"': return json_type::string; case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } +#endif return json_type::null; case 't': case 'f': return json_type::boolean; @@ -124267,6 +132280,14 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return json_type::number; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; + case 'I': case 'i': + if (atomparsing::is_valid_inf_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; +#endif default: return json_type::unknown; } @@ -125691,6 +133712,12 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 64 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + // Masked-off bytes are not read, so they cannot fault. + return _mm512_mask_loadu_epi8(_mm512_set1_epi8(char(fill)), (uint64_t(1) << n) - 1, ptr); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m512i _value) : base8_numeric(_value) {} // Splat constructor @@ -127384,6 +135411,23 @@ class value { */ simdjson_inline std::string_view raw_json_token() noexcept; + /** + * Calls the visitor for this value and everything in it, as document::visit() does for a + * whole document, for example after navigating to a field: + * + * auto error = doc["payload"].visit(visitor); + * + * The value must not have been read. The walk does not move the iterator: to go on, read the + * value or the next field or element as usual. A string with escapes is valid until you read + * the document further or visit again. The maximal depth counts from the root of the document. + * A value at the root also fails if anything follows it. + * + * @returns SUCCESS, OUT_OF_ORDER_ITERATION if the value has been read, the first error found + * in the value, or the first error the visitor returns. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); + /** * Get a string_view pointing at this value in the JSON document. * If this element is an array or an object, it consumes the array or the object @@ -127701,6 +135745,8 @@ struct simdjson_result : public icelake::implementatio /** @copydoc simdjson_inline std::string_view value::raw_json_token() const noexcept */ simdjson_inline simdjson_result raw_json_token() noexcept; simdjson_inline simdjson_result raw_json() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** @copydoc simdjson_inline simdjson_result current_location() noexcept */ simdjson_inline simdjson_result current_location() noexcept; @@ -128046,6 +136092,29 @@ class json_iterator { simdjson_inline error_code out_of_place_error() noexcept; /** Tells whether the string before pos, followed by a colon, is a key. */ static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; + /** + * Validates the array or object at the current position and everything in it, without + * recursion. Outside of streaming mode, it also checks that nothing follows it. It does + * not move the iterator. + */ + simdjson_warn_unused error_code validate_container() noexcept; + static simdjson_inline bool has_backslash(const uint8_t *src, size_t len) noexcept; + /** + * Calls the visitor for the array or object at the start position and everything in it, + * without recursion (see document::visit()). The container is at depth parent_depth + 1. At + * the root (parent_depth == 0) and outside of streaming mode, it also checks that nothing + * follows it. It does not move the iterator. Escaped strings are copied into the string + * buffer. + */ + template + simdjson_warn_unused error_code visit_container(V &visitor, token_position start, size_t parent_depth); + template + simdjson_warn_unused simdjson_inline error_code visit_string(const uint8_t *quote, bool key, V &visitor); + template + simdjson_warn_unused simdjson_inline error_code visit_scalar(const uint8_t *src, V &visitor); + /** Calls the visitor for a number that numberparsing::parse_number accepted. */ + template + static simdjson_warn_unused simdjson_inline error_code visit_number(const number &value, const char *raw, V &visitor); /** * Tell whether the iterator is still at the start @@ -128235,7 +136304,8 @@ class json_iterator { /** * Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with * N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero. - * Trailing whitespace, commas, and record separators (0x1E) do not count toward max_len. + * Trailing whitespace does not count toward max_len. A comma or record + * separator (0x1E) is ignored only for a document stream. * The buffer (tmpbuf) is padded with space characters. */ simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept; @@ -128931,6 +137001,33 @@ class parser { */ simdjson_warn_unused simdjson_result iterate_raw(padded_string_view json) & noexcept; + /** + * Parses the document and walks it once with the visitor: the same as iterate() followed by + * document::visit(), with the same values and, when the visitor returns SUCCESS, the same + * error code, but faster on small documents. + * + * counting_visitor visitor; + * auto error = parser.visit(R"({"stars":[1,2,3]})"_padded, visitor); + * + * A document of at most MAX_ONE_PASS_VISIT bytes whose root is an object or an array is read in + * a single pass, without the structural index that iterate() builds. Some checks, such as the + * UTF-8 validation, then come at the end of the walk: on an invalid document, the visitor may + * have seen part or all of it before visit() returns the error code of document::visit(), and + * an error returned by the visitor may come first. With SIMDJSON_ENABLE_NAN_INF or + * SIMDJSON_ALLOW_TRAILING_COMMAS, there is no one-pass walk. + * + * See document::visit() for the methods of the visitor and the lifetime of the strings. + * + * @param json The JSON to parse, with at least SIMDJSON_PADDING bytes after it. + * @param visitor The visitor. + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(padded_string_view json, V &visitor) &; + /** Documents of at most this many bytes may be visited in one pass, see visit(). */ + static constexpr size_t MAX_ONE_PASS_VISIT = 32; + /** * Parse a buffer containing many JSON documents. @@ -129089,6 +137186,20 @@ class parser { */ simdjson_pure simdjson_inline size_t max_depth() const noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the string buffer and the structural indexes) through a buffer_allocator. + * nullptr, the default, uses new[]. The allocator must outlive the parser. + * + * Buffers that the parser already holds keep the allocator that allocated + * them until the parser grows them, so set the allocator before the first + * document or the first call to allocate(). A failed allocation makes the + * parser return MEMALLOC and leaves its buffers as they were. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + /** * Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length * and `max_depth` depth. @@ -129198,17 +137309,27 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr& get_threadlocal_parser_if_exists(); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + simdjson_inline void drop_trailing_commas(const uint8_t *buf) noexcept; +#endif #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** + * The one-pass walk of visit(). Returns UNINITIALIZED when it does not handle the document, + * and TAPE_ERROR when the document is invalid. visitor_failed tells an error of the visitor. + */ + template + simdjson_warn_unused simdjson_inline error_code visit_one_pass(const uint8_t *buf, size_t len, V &visitor, bool &visitor_failed); /** @private [for benchmarking access] The implementation to use */ std::unique_ptr implementation{}; size_t _capacity{0}; size_t _max_capacity; size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; - std::unique_ptr string_buf{}; + simdjson::internal::allocated_array string_buf{}; + const buffer_allocator *_allocator{nullptr}; #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; @@ -130466,6 +138587,58 @@ class document { * left as is. */ inline void rewind() noexcept; + /** + * Validates the whole document: its structure, every string (escapes included), every + * number, true, false and null, and that nothing follows the root value. Strings are + * checked as get_string() checks them and numbers as get_double() does. The document is + * rewound before and after, so that it can be iterated after a successful validation. + * + * It is faster than iterating through every value, because it walks the tokens directly, + * without creating values, arrays or objects. + * + * @returns SUCCESS if the document is valid, or the error found first. + */ + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + /** + * Walks the whole document once and calls the visitor for each value, in document order. + * Use it to build your own representation of the document (a tree, columns, ...) faster + * than by iterating, as the walk creates no values, arrays or objects. + * + * The visitor provides these methods. Each returns an error_code: anything but SUCCESS stops + * the walk, and visit() returns it. + * + * error_code on_object_start(); + * error_code on_object_end(uint32_t member_count); + * error_code on_array_start(); + * error_code on_array_end(uint32_t element_count); + * error_code on_key(std::string_view key); // before each member value + * error_code on_string(std::string_view value); + * error_code on_int64(int64_t value, const char *raw); // integers that fit an int64_t + * error_code on_uint64(uint64_t value, const char *raw); // larger positive integers + * error_code on_double(double value, const char *raw); + * error_code on_bool(bool value); + * error_code on_null(); + * + * raw points at the number in the document, so that the visitor can tell -0 from 0, for + * example. As with the DOM parser, an integer that does not fit in 64 bits is a BIGINT_ERROR. + * + * A key or a string without escapes is a view into the document: it is valid as long as the + * document's bytes are. A key or a string with escapes is unescaped into the parser: it is + * valid until the document is iterated or visited again, or the parser parses another + * document. + * + * visit() succeeds exactly when the DOM parser does. An error may come after the visitor has + * seen part of the document. The document is rewound before and after the walk, so that it + * can be iterated afterwards. The visitor may throw: the exception goes through visit(), and + * the document must then be rewound before it is used again. + * + * To parse and visit a document in one call, faster on small documents, see parser::visit(). + * + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** * Returns debugging information. */ @@ -130636,6 +138809,9 @@ class document { simdjson_inline value_iterator resume_value_iterator() noexcept; simdjson_inline value_iterator get_root_value_iterator() noexcept; + /** The walk of visit(), between its two rewinds. */ + template + simdjson_warn_unused simdjson_inline error_code visit_root(V &visitor); simdjson_inline simdjson_result start_or_resume_object() noexcept; static simdjson_inline document start(ondemand::json_iterator &&iter) noexcept; @@ -130855,6 +139031,9 @@ struct simdjson_result : public icelake::implementa simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); simdjson_inline simdjson_result get_array() & noexcept; simdjson_inline simdjson_result get_object() & noexcept; @@ -134142,6 +142321,7 @@ inline std::ostream& operator<<(std::ostream& out, simdjson::simdjson_result #include +#include #if SIMDJSON_STATIC_REFLECTION #include #include @@ -134351,9 +142531,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { SIMDJSON_TRY(v.get(scratch.elements.emplace_back())); release.parsed++; } - out.reserve(release.parsed); - release.complete = true; - for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + if constexpr (std::is_trivially_copyable_v) { + out.assign(scratch.elements.begin(), scratch.elements.end()); + release.complete = true; + } else if (sizeof(value_type) <= 32 && scratch.elements.capacity() / 2 < release.parsed) { + // Hand the buffer over only when it is at least half full, so that out + // does not keep the capacity of an earlier, larger array. Swapping + // large structs is slower than moving them (recipe_book benchmark). + size_t const capacity = scratch.elements.capacity(); + out.swap(scratch.elements); + release.complete = true; + if (capacity * sizeof(value_type) <= (1 << 20)) { scratch.elements.reserve(capacity); } + } else { + out.reserve(release.parsed); + release.complete = true; + for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + } return SUCCESS; } } @@ -134583,7 +142776,11 @@ consteval void append_eligible_fields(std::meta::info type, std::vector(std::meta::substitute(^^flattenable_type, {flattened}))) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member whose type is a structure deserialized member by member", mem); +#else + simdjson::detail::flatten_requires_a_member_deserialized_member_by_member(); +#endif } append_eligible_fields(flattened, prefix, fields); } else { @@ -135939,6 +144136,27 @@ simdjson_warn_unused simdjson_inline simdjson_result value::get_number() return iter.get_number(); } +template +simdjson_warn_unused simdjson_inline error_code value::visit(V &visitor) { + if (!iter.is_at_start()) { return OUT_OF_ORDER_ITERATION; } + json_iterator &json_iter = iter.json_iter(); + const uint8_t *const json = iter.peek_start(); + // The escaped strings of the value go where reading it would put them, so that the string + // buffer has room for them however many times the value is visited. + uint8_t *const string_buf_loc = json_iter._string_buf_loc; + error_code error; + switch (*json) { + case '{': case '[': + error = json_iter.visit_container(visitor, iter.start_position(), size_t(iter.depth() - 1)); + break; + // A scalar value is nested in a container: its parser reads inside the document. + case '"': error = json_iter.visit_string(json, false, visitor); break; + default: error = json_iter.visit_scalar(json, visitor); break; + } + json_iter._string_buf_loc = string_buf_loc; + return error; +} + simdjson_inline std::string_view value::raw_json_token() noexcept { return std::string_view(reinterpret_cast(iter.peek_start()), iter.peek_start_length()); } @@ -136350,6 +144568,12 @@ simdjson_inline simdjson_result::operator bool() noexc } #endif +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + simdjson_inline simdjson_result simdjson_result::raw_json_token() noexcept { if (error()) { return error(); } return first.raw_json_token(); @@ -136445,6 +144669,124 @@ inline void document::rewind() noexcept { static_cast(iter.rewind()); } +simdjson_warn_unused simdjson_inline error_code document::validate() noexcept { + SIMDJSON_TRY(iter.rewind()); + const bool check_trailing = !iter.streaming(); + const uint8_t first = *iter.peek(); + error_code error; + switch (first) { + case '{': case '[': + error = iter.validate_container(); + break; + case '"': + error = get_root_value_iterator().get_root_string(check_trailing, false).error(); + break; + case 't': case 'f': + error = get_root_value_iterator().get_root_bool(check_trailing).error(); + break; + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && !null_value) { error = N_ATOM_ERROR; } +#if SIMDJSON_ENABLE_NAN_INF + if (error && !get_root_value_iterator().get_root_double(check_trailing).error()) { error = SUCCESS; } +#endif + break; + } + default: + error = get_root_value_iterator().get_root_double(check_trailing).error(); + break; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit(V &visitor) { + SIMDJSON_TRY(iter.rewind()); + const error_code error = visit_root(visitor); + // The strings of the walk stay in the buffer, but an iteration may start from its beginning. + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit_root(V &visitor) { + const bool check_trailing = !iter.streaming(); + const uint8_t *const first = iter.peek(); + const char *const raw = reinterpret_cast(first); + error_code error; + switch (*first) { + case '{': case '[': + return iter.visit_container(visitor, iter.position(), 0); + case '"': { + raw_json_string text; + error = get_root_value_iterator().get_root_raw_json_string(check_trailing).get(text); + if (!error) { return iter.visit_string(first, false, visitor); } + break; + } + case 't': case 'f': { + bool value; + error = get_root_value_iterator().get_root_bool(check_trailing).get(value); + if (!error) { return visitor.on_bool(value); } + break; + } + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && null_value) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + double value; + if (!get_root_value_iterator().get_root_double(check_trailing).get(value)) { return visitor.on_double(value, raw); } +#endif + if (!error) { error = N_ATOM_ERROR; } + break; + } + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + number value; + error = get_root_value_iterator().get_root_number(check_trailing).get(value); + if (!error) { return json_iterator::visit_number(value, raw, visitor); } + break; + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': { + double value; + error = get_root_value_iterator().get_root_double(check_trailing).get(value); + if (!error) { return visitor.on_double(value, raw); } + return error == TRAILING_CONTENT ? error : TAPE_ERROR; + } +#endif + default: + return TAPE_ERROR; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (*first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + return error; +} + inline std::string document::to_debug_string() noexcept { return iter.to_string(); } @@ -136999,6 +145341,16 @@ simdjson_inline error_code simdjson_result::rewind( first.rewind(); return SUCCESS; } +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + +simdjson_warn_unused simdjson_inline error_code simdjson_result::validate() noexcept { + if (error()) { return error(); } + return first.validate(); +} simdjson_inline simdjson_result simdjson_result::begin() & noexcept { if (error()) { return error(); } return first.begin(); @@ -138069,6 +146421,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } worker->start_thread(); @@ -138322,6 +146675,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch @@ -138337,6 +146693,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -138678,6 +147037,8 @@ simdjson_inline simdjson_result simdjson_result= 8; src += 8, len -= 8) { + std::memcpy(&word, src, sizeof(word)); + word ^= BACKSLASHES; + if ((word - ONES) & ~word & HIGHS) { return true; } + } + uint64_t keep; + std::memcpy(&keep, KEEP + 8 - len, sizeof(keep)); + std::memcpy(&word, src, sizeof(word)); + word = (word ^ BACKSLASHES) | ~keep; + return ((word - ONES) & ~word & HIGHS) != 0; +} + +simdjson_warn_unused simdjson_never_inline error_code json_iterator::validate_container() noexcept { + const uint8_t *const json = token.buf; + token_position pos = token.position(); + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // One bit per depth tells whether the container at that depth is an array. Deeper than + // the fixed stack allows, the bits move to the heap. + uint64_t fixed_stack[16]{}; + std::unique_ptr heap_stack; + uint64_t *is_array = fixed_stack; + size_t depth = 0; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VALIDATE_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VALIDATE_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': goto scalar_string; + default: goto scalar; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. Its bit may then + // be at max_depth, which the stack has room for. + if (++depth >= max_depth && (pos == end || json[*pos] != c + 2)) { return DEPTH_ERROR; } + // The bits move once: the next time this depth is reached, the heap holds the current + // bits and the fixed stack holds stale ones. + if (depth == sizeof(fixed_stack) * 8 && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint64_t[max_depth / 64 + 1]()); + if (!heap_stack) { return MEMALLOC; } + std::memcpy(heap_stack.get(), fixed_stack, sizeof(fixed_stack)); + is_array = heap_stack.get(); + } + if (c == '[') { + is_array[depth / 64] |= uint64_t(1) << (depth % 64); + SIMDJSON_VALIDATE_NEXT(); + if (c == ']') { goto container_end; } + goto value; + } + is_array[depth / 64] &= ~(uint64_t(1) << (depth % 64)); + SIMDJSON_VALIDATE_NEXT(); + if (c == '}') { goto container_end; } + goto key; + +key: + if (c != '"') { return TAPE_ERROR; } + // A string is valid once stage 1 has accepted the document, unless it holds an escape. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + SIMDJSON_VALIDATE_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VALIDATE_NEXT(); + goto value; + +scalar_string: + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + goto value_end; + +scalar: + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + break; + default: + return TAPE_ERROR; + } + // The scalar is not the last token, so the parsers read inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + switch (c) { + case 't': if (!atomparsing::is_valid_true_atom(json + index)) { return T_ATOM_ERROR; } break; + case 'f': if (!atomparsing::is_valid_false_atom(json + index)) { return F_ATOM_ERROR; } break; + case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (!atomparsing::is_valid_null_atom(json + index) && !atomparsing::is_valid_nan_atom(json + index)) { return N_ATOM_ERROR; } +#else + if (!atomparsing::is_valid_null_atom(json + index)) { return N_ATOM_ERROR; } +#endif + break; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': if (!atomparsing::is_valid_nan_atom(json + index)) { return TAPE_ERROR; } break; + case 'i': case 'I': if (!atomparsing::is_valid_inf_atom(json + index)) { return TAPE_ERROR; } break; +#endif + default: + if (numberparsing::parse_double(json + index).error()) { return NUMBER_ERROR; } + break; + } + +value_end: + SIMDJSON_VALIDATE_NEXT(); + if (c == ',') { + SIMDJSON_VALIDATE_NEXT(); + if (is_array[depth / 64] & (uint64_t(1) << (depth % 64))) { goto value; } + goto key; + } + if (c != (is_array[depth / 64] & (uint64_t(1) << (depth % 64)) ? ']' : '}')) { return TAPE_ERROR; } + +container_end: + if (--depth > 0) { goto value_end; } +#undef SIMDJSON_VALIDATE_NEXT + if (!streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_number(const number &value, const char *raw, V &visitor) { + switch (value.get_number_type()) { + case number_type::signed_integer: return visitor.on_int64(value.get_int64(), raw); + case number_type::unsigned_integer: return visitor.on_uint64(value.get_uint64(), raw); + case number_type::floating_point_number: return visitor.on_double(value.get_double(), raw); + default: return BIGINT_ERROR; + } +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_string(const uint8_t *quote, bool key, V &visitor) { + const uint8_t *const start = quote + 1; + // A string without escapes is passed as it is in the document. + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (const uint8_t *src = start;; src += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(src, scratch); + if (bs_quote.has_quote_first()) { + std::string_view text(reinterpret_cast(start), size_t(src - start) + size_t(bs_quote.quote_index())); + return key ? visitor.on_key(text) : visitor.on_string(text); + } + if (bs_quote.has_backslash()) { break; } + } + uint8_t *const end = parser->implementation->parse_string(start, _string_buf_loc, false); + if (!end) { return STRING_ERROR; } + std::string_view text(reinterpret_cast(_string_buf_loc), size_t(end - _string_buf_loc)); + _string_buf_loc = end; + return key ? visitor.on_key(text) : visitor.on_string(text); +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_scalar(const uint8_t *src, V &visitor) { + switch (*src) { + case 't': return atomparsing::is_valid_true_atom(src) ? visitor.on_bool(true) : T_ATOM_ERROR; + case 'f': return atomparsing::is_valid_false_atom(src) ? visitor.on_bool(false) : F_ATOM_ERROR; + case 'n': + if (atomparsing::is_valid_null_atom(src)) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } +#endif + return N_ATOM_ERROR; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + number value; + SIMDJSON_TRY(numberparsing::parse_number(src, value)); + return visit_number(value, reinterpret_cast(src), visitor); + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } + return TAPE_ERROR; + case 'i': case 'I': + if (atomparsing::is_valid_inf_atom(src)) { return visitor.on_double(std::numeric_limits::infinity(), reinterpret_cast(src)); } + return TAPE_ERROR; +#endif + default: + return TAPE_ERROR; + } +} + +template +simdjson_warn_unused error_code json_iterator::visit_container(V &visitor, token_position start, size_t parent_depth) { + const uint8_t *const json = token.buf; + token_position pos = start; + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // For each open container, the number of its elements so far, with the top bit set for an + // array. Deeper than the fixed stack allows, the stack moves to the heap. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + constexpr size_t FIXED_DEPTH = 64; + uint32_t fixed_stack[FIXED_DEPTH]; + std::unique_ptr heap_stack; + uint32_t *stack = fixed_stack; + size_t depth = parent_depth; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VISIT_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VISIT_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': + // A string is not the last token, so that its closing quote is inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, false, visitor)); + goto value_end; + default: + // The scalar is not the last token, so the parsers read inside the document. + if (simdjson_unlikely(pos == end)) { + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + return INCOMPLETE_ARRAY_OR_OBJECT; + default: + return TAPE_ERROR; + } + } + SIMDJSON_TRY(visit_scalar(json + index, visitor)); + goto value_end; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. + if (pos != end && json[*pos] == c + 2) { + pos++; + if (c == '[') { + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_TRY(visitor.on_array_end(0)); + } else { + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_TRY(visitor.on_object_end(0)); + } + if (depth == parent_depth) { goto document_end; } + goto value_end; + } + if (++depth >= max_depth) { return DEPTH_ERROR; } + // Copy the fixed stack once. A later container at this depth must keep the + // counts already stored on the heap. + if (depth >= FIXED_DEPTH && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint32_t[max_depth]); + if (!heap_stack) { return MEMALLOC; } + // Only the slots past the parent were written. + if (parent_depth + 1 < FIXED_DEPTH) { + std::memcpy(heap_stack.get() + parent_depth + 1, fixed_stack + parent_depth + 1, (FIXED_DEPTH - parent_depth - 1) * sizeof(fixed_stack[0])); + } + stack = heap_stack.get(); + } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_VISIT_NEXT(); + goto value; + } + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_VISIT_NEXT(); + +key: + if (c != '"') { return TAPE_ERROR; } + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, true, visitor)); + SIMDJSON_VISIT_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VISIT_NEXT(); + goto value; + +value_end: + SIMDJSON_VISIT_NEXT(); + if (c == ',') { + stack[depth]++; + SIMDJSON_VISIT_NEXT(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_object_end(stack[depth])); + } + if (--depth > parent_depth) { goto value_end; } + +document_end: +#undef SIMDJSON_VISIT_NEXT + if (parent_depth == 0 && !streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + simdjson_inline bool json_iterator::at_root() const noexcept { return position() == root_position(); } @@ -139318,10 +148008,20 @@ simdjson_warn_unused simdjson_inline bool json_iterator::copy_to_buffer(const ui // peek_root_length() stops at the next structural index. Stage 1 omits the // comma or RS (0x1E) that separates stream documents, so that byte and the // whitespace around it remain in the span. RS is not a valid number finisher. + // Outside of a stream, the comma and RS are not separators: some kernels + // keep RS in the scalar token, and dropping it would accept "1\x1e". while (max_len > 0) { const uint8_t last = json[max_len - 1]; + // iterate_allow_incomplete_json() reuses _streaming, so a root scalar + // there is not a document_stream. +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + const bool separator = _streaming && !_allow_incomplete_json && + (last == ',' || last == 0x1E); +#else + const bool separator = _streaming && (last == ',' || last == 0x1E); +#endif if (last != ' ' && last != '\t' && last != '\n' && last != '\r' && - last != ',' && last != 0x1E) { + !separator) { break; } max_len--; @@ -140751,22 +149451,22 @@ simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capa return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - std::unique_ptr new_string_buf(new (std::nothrow) uint8_t[string_capacity]); - if (!new_string_buf) { return MEMALLOC; } + simdjson::internal::allocated_array new_string_buf; + if (!new_string_buf.allocate(string_capacity, _allocator)) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr new_start_positions(new (std::nothrow) token_position[new_max_depth]); if (!new_start_positions) { return MEMALLOC; } #endif - if (implementation) { - error_code err = implementation->allocate(new_capacity, new_max_depth); - if (err) { return err; } - } else { - error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, new_max_depth, implementation); if (err) { implementation.reset(); return err; } } + implementation->allocator = _allocator; + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } string_buf = std::move(new_string_buf); #if SIMDJSON_DEVELOPMENT_CHECKS start_positions = std::move(new_start_positions); @@ -140795,9 +149495,42 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iterate(p // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return document::start({ reinterpret_cast(json.data()), this }); } +// Removes from the structural indexes each comma that follows a value and +// precedes a closing bracket, so that the iterator never sees it. The entries +// past the last index (stage 1 keeps up to three there) move with the others. +#if SIMDJSON_ALLOW_TRAILING_COMMAS +simdjson_inline void parser::drop_trailing_commas(const uint8_t *buf) noexcept { + uint32_t *indexes = implementation->structural_indexes.get(); + const uint32_t n = implementation->n_structural_indexes; + uint32_t kept = 0; + uint8_t previous = '['; + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = buf[indexes[i]]; + if (c == ',' && i + 1 < n && previous != '[' && previous != '{' && previous != ',' && previous != ':') { + const uint8_t next = buf[indexes[i + 1]]; + if (next == ']' || next == '}') { + previous = c; + continue; + } + } + indexes[kept++] = indexes[i]; + previous = c; + } + if (kept != n) { + indexes[kept] = indexes[n]; + indexes[kept + 1] = indexes[n + 1]; + indexes[kept + 2] = indexes[n + 2]; + implementation->n_structural_indexes = kept; + } +} +#endif // SIMDJSON_ALLOW_TRAILING_COMMAS + #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_warn_unused simdjson_inline simdjson_result parser::iterate_allow_incomplete_json(padded_string_view json) & noexcept { if (!json.has_sufficient_padding()) { return INSUFFICIENT_PADDING; } @@ -140901,9 +149634,210 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iter // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return json_iterator(reinterpret_cast(json.data()), this); } +namespace { +struct ignoring_visitor { + simdjson_inline error_code on_object_start() { return SUCCESS; } + simdjson_inline error_code on_object_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_array_start() { return SUCCESS; } + simdjson_inline error_code on_array_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_key(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_string(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_int64(int64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_uint64(uint64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_double(double, const char *) { return SUCCESS; } + simdjson_inline error_code on_bool(bool) { return SUCCESS; } + simdjson_inline error_code on_null() { return SUCCESS; } +}; +} // unnamed namespace + +template +simdjson_warn_unused simdjson_inline error_code parser::visit(padded_string_view json, V &visitor) & { +#if !SIMDJSON_ENABLE_NAN_INF && !SIMDJSON_ALLOW_TRAILING_COMMAS + if (json.length() <= MAX_ONE_PASS_VISIT && json.has_sufficient_padding()) { + if (capacity() < json.length() || !string_buf) { + SIMDJSON_TRY( allocate(json.length(), max_depth()) ); + } + bool visitor_failed = false; + const error_code error = visit_one_pass(reinterpret_cast(json.data()), json.length(), visitor, visitor_failed); + if (error != UNINITIALIZED) { + if (error != TAPE_ERROR || visitor_failed) { return error; } + // The visitor has already seen part of the document: the regular walk only finds the + // error code, and never calls the visitor a second time. + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + ignoring_visitor ignoring; + const error_code regular_error = doc.visit(ignoring); + return regular_error ? regular_error : TAPE_ERROR; + } + } +#endif + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + return doc.visit(visitor); +} + +// A single pass over the bytes, for small documents. The root must be an array or an object, and +// the last byte that is not whitespace must be ] or }: before it, runs of whitespace, digits or +// atoms stop without a bound check. Only a closing bracket or a string may reach the end. +template +simdjson_warn_unused simdjson_inline error_code parser::visit_one_pass(const uint8_t *const buf, const size_t len, V &visitor, bool &visitor_failed) { + const auto is_whitespace = [](uint8_t c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; + if (len == 0 || len > MAX_ONE_PASS_VISIT) { return UNINITIALIZED; } + const uint8_t *p = buf; + const uint8_t *last = buf + len - 1; + while (p < last && is_whitespace(*p)) { p++; } + while (last > p && is_whitespace(*last)) { last--; } + if ((*p != '{' && *p != '[') || (*last != '}' && *last != ']')) { return UNINITIALIZED; } + const uint8_t *const end = last + 1; + uint8_t *dst = string_buf.get(); + bool non_ascii = false; + // For each open container, the number of its elements so far, with the top bit set for an + // array. Each container opens at a distinct byte before the last one, so that the depth stays + // below MAX_ONE_PASS_VISIT. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + uint32_t stack[MAX_ONE_PASS_VISIT]; + size_t depth = 0; + uint8_t c = *p; + +#define SIMDJSON_ONE_PASS_CALL(EXPR) \ + do { \ + const error_code one_pass_error = (EXPR); \ + if (simdjson_unlikely(one_pass_error != SUCCESS)) { visitor_failed = true; return one_pass_error; } \ + } while (0) +#define SIMDJSON_ONE_PASS_WHITESPACE() while (is_whitespace(*p)) { p++; } +// The string at p, which is left past the closing quote. +#define SIMDJSON_ONE_PASS_STRING(METHOD) \ + do { \ + const uint8_t *const start = ++p; \ + bool escaped = false; \ + for (;; p++) { \ + if (simdjson_unlikely(p >= end)) { return TAPE_ERROR; } \ + if (*p == '"') { break; } \ + if (*p == '\\') { \ + escaped = true; \ + p++; \ + } else if (simdjson_unlikely(*p < 0x20)) { \ + return TAPE_ERROR; \ + } else if (*p >= 0x80) { \ + non_ascii = true; \ + } \ + } \ + std::string_view text(reinterpret_cast(start), size_t(p - start)); \ + p++; \ + if (escaped) { \ + uint8_t *const unescaped_end = implementation->parse_string(start, dst, false); \ + if (unescaped_end == nullptr) { return TAPE_ERROR; } \ + text = std::string_view(reinterpret_cast(dst), size_t(unescaped_end - dst)); \ + dst = unescaped_end; \ + } \ + SIMDJSON_ONE_PASS_CALL(visitor.METHOD(text)); \ + } while (0) + + goto container_start; + +value: + switch (*p) { + case '{': case '[': + c = *p; + goto container_start; + case '"': + SIMDJSON_ONE_PASS_STRING(on_string); + goto value_end; + case 't': + if (!atomparsing::is_valid_true_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(true)); + p += 4; + goto value_end; + case 'f': + if (!atomparsing::is_valid_false_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(false)); + p += 5; + goto value_end; + case 'n': + if (!atomparsing::is_valid_null_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_null()); + p += 4; + goto value_end; + default: { + number value; + if (numberparsing::parse_number(p, value) != SUCCESS) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(json_iterator::visit_number(value, reinterpret_cast(p), visitor)); + while (jsoncharutils::is_not_structural_or_whitespace(*p)) { p++; } + goto value_end; + } + } + +container_start: + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + // As in DOM, an empty container does not count toward the maximal depth. + if (*p == c + 2) { + p++; + if (c == '[') { + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(0)); + } else { + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(0)); + } + if (depth == 0) { goto document_end; } + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + if (++depth >= max_depth()) { return TAPE_ERROR; } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + goto value; + } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + +key: + if (*p != '"') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_STRING(on_key); + SIMDJSON_ONE_PASS_WHITESPACE(); + if (*p != ':') { return TAPE_ERROR; } + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + goto value; + +value_end: + SIMDJSON_ONE_PASS_WHITESPACE(); + c = *p++; + if (c == ',') { + stack[depth]++; + SIMDJSON_ONE_PASS_WHITESPACE(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(stack[depth])); + } + if (--depth > 0) { + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + +document_end: +#undef SIMDJSON_ONE_PASS_CALL +#undef SIMDJSON_ONE_PASS_WHITESPACE +#undef SIMDJSON_ONE_PASS_STRING + if (p != end) { return TAPE_ERROR; } + if (non_ascii && !simdjson::validate_utf8(reinterpret_cast(buf), len)) { return TAPE_ERROR; } + return SUCCESS; +} + inline simdjson_result parser::iterate_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept { if(batch_size < MINIMAL_BATCH_SIZE) { batch_size = MINIMAL_BATCH_SIZE; } if((len >= 3) && (std::memcmp(buf, "\xEF\xBB\xBF", 3) == 0)) { @@ -141021,6 +149955,13 @@ simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return _max_depth; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} + simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept { if(max_capacity > dom::MINIMAL_DOCUMENT_CAPACITY) { _max_capacity = max_capacity; @@ -141540,13 +150481,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_objec _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing } at end"); } - // If the last character is } *and* the first gibberish character is also '}' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is } *and* the first gibberish character is '}', ']' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == '}') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed object. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -141950,13 +150893,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_array _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing ] at end"); } - // If the last character is ] *and* the first gibberish character is also ']' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is ] *and* the first gibberish character is ']', '}' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == ']') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed array. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -142126,7 +151071,7 @@ simdjson_inline simdjson_result value_iterator::get_root_n // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -142150,7 +151095,7 @@ simdjson_inline simdjson_result value_iterator::get_root_number(bool che // number: -0.e-308. // NOTE: the current approach doesn't work for very big integer numbers containing more than 1074 digits. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -142232,7 +151177,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::g simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer tmpbuf[20+1] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+1)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 20 characters"); @@ -142249,7 +151194,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::ge simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64_in_string(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer tmpbuf[20+2] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+2)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 22 characters"); @@ -142270,7 +151215,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -142292,7 +151237,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -142314,7 +151259,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ // digits that matter is smaller for binary32, but the JSON document may still // spell out a long number that we must parse (and round) faithfully. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -142333,7 +151278,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ auto max_len = peek_root_length(); auto json = peek_root_scalar("float"); // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -142671,6 +151616,9 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '"': return json_type::string; case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } +#endif return json_type::null; case 't': case 'f': return json_type::boolean; @@ -142678,6 +151626,14 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return json_type::number; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; + case 'I': case 'i': + if (atomparsing::is_valid_inf_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; +#endif default: return json_type::unknown; } @@ -143861,6 +152817,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/ppc64/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/ppc64/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -143876,7 +152833,6 @@ namespace ppc64 { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; @@ -143888,9 +152844,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars val = bswap64(val); #endif #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -144216,6 +153170,14 @@ template <> struct simd8 : base8_numeric { // Unsigned bytes template <> struct simd8 : base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} @@ -145916,6 +154878,23 @@ class value { */ simdjson_inline std::string_view raw_json_token() noexcept; + /** + * Calls the visitor for this value and everything in it, as document::visit() does for a + * whole document, for example after navigating to a field: + * + * auto error = doc["payload"].visit(visitor); + * + * The value must not have been read. The walk does not move the iterator: to go on, read the + * value or the next field or element as usual. A string with escapes is valid until you read + * the document further or visit again. The maximal depth counts from the root of the document. + * A value at the root also fails if anything follows it. + * + * @returns SUCCESS, OUT_OF_ORDER_ITERATION if the value has been read, the first error found + * in the value, or the first error the visitor returns. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); + /** * Get a string_view pointing at this value in the JSON document. * If this element is an array or an object, it consumes the array or the object @@ -146233,6 +155212,8 @@ struct simdjson_result : public ppc64::implementation_si /** @copydoc simdjson_inline std::string_view value::raw_json_token() const noexcept */ simdjson_inline simdjson_result raw_json_token() noexcept; simdjson_inline simdjson_result raw_json() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** @copydoc simdjson_inline simdjson_result current_location() noexcept */ simdjson_inline simdjson_result current_location() noexcept; @@ -146578,6 +155559,29 @@ class json_iterator { simdjson_inline error_code out_of_place_error() noexcept; /** Tells whether the string before pos, followed by a colon, is a key. */ static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; + /** + * Validates the array or object at the current position and everything in it, without + * recursion. Outside of streaming mode, it also checks that nothing follows it. It does + * not move the iterator. + */ + simdjson_warn_unused error_code validate_container() noexcept; + static simdjson_inline bool has_backslash(const uint8_t *src, size_t len) noexcept; + /** + * Calls the visitor for the array or object at the start position and everything in it, + * without recursion (see document::visit()). The container is at depth parent_depth + 1. At + * the root (parent_depth == 0) and outside of streaming mode, it also checks that nothing + * follows it. It does not move the iterator. Escaped strings are copied into the string + * buffer. + */ + template + simdjson_warn_unused error_code visit_container(V &visitor, token_position start, size_t parent_depth); + template + simdjson_warn_unused simdjson_inline error_code visit_string(const uint8_t *quote, bool key, V &visitor); + template + simdjson_warn_unused simdjson_inline error_code visit_scalar(const uint8_t *src, V &visitor); + /** Calls the visitor for a number that numberparsing::parse_number accepted. */ + template + static simdjson_warn_unused simdjson_inline error_code visit_number(const number &value, const char *raw, V &visitor); /** * Tell whether the iterator is still at the start @@ -146767,7 +155771,8 @@ class json_iterator { /** * Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with * N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero. - * Trailing whitespace, commas, and record separators (0x1E) do not count toward max_len. + * Trailing whitespace does not count toward max_len. A comma or record + * separator (0x1E) is ignored only for a document stream. * The buffer (tmpbuf) is padded with space characters. */ simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept; @@ -147463,6 +156468,33 @@ class parser { */ simdjson_warn_unused simdjson_result iterate_raw(padded_string_view json) & noexcept; + /** + * Parses the document and walks it once with the visitor: the same as iterate() followed by + * document::visit(), with the same values and, when the visitor returns SUCCESS, the same + * error code, but faster on small documents. + * + * counting_visitor visitor; + * auto error = parser.visit(R"({"stars":[1,2,3]})"_padded, visitor); + * + * A document of at most MAX_ONE_PASS_VISIT bytes whose root is an object or an array is read in + * a single pass, without the structural index that iterate() builds. Some checks, such as the + * UTF-8 validation, then come at the end of the walk: on an invalid document, the visitor may + * have seen part or all of it before visit() returns the error code of document::visit(), and + * an error returned by the visitor may come first. With SIMDJSON_ENABLE_NAN_INF or + * SIMDJSON_ALLOW_TRAILING_COMMAS, there is no one-pass walk. + * + * See document::visit() for the methods of the visitor and the lifetime of the strings. + * + * @param json The JSON to parse, with at least SIMDJSON_PADDING bytes after it. + * @param visitor The visitor. + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(padded_string_view json, V &visitor) &; + /** Documents of at most this many bytes may be visited in one pass, see visit(). */ + static constexpr size_t MAX_ONE_PASS_VISIT = 32; + /** * Parse a buffer containing many JSON documents. @@ -147621,6 +156653,20 @@ class parser { */ simdjson_pure simdjson_inline size_t max_depth() const noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the string buffer and the structural indexes) through a buffer_allocator. + * nullptr, the default, uses new[]. The allocator must outlive the parser. + * + * Buffers that the parser already holds keep the allocator that allocated + * them until the parser grows them, so set the allocator before the first + * document or the first call to allocate(). A failed allocation makes the + * parser return MEMALLOC and leaves its buffers as they were. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + /** * Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length * and `max_depth` depth. @@ -147730,17 +156776,27 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr& get_threadlocal_parser_if_exists(); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + simdjson_inline void drop_trailing_commas(const uint8_t *buf) noexcept; +#endif #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** + * The one-pass walk of visit(). Returns UNINITIALIZED when it does not handle the document, + * and TAPE_ERROR when the document is invalid. visitor_failed tells an error of the visitor. + */ + template + simdjson_warn_unused simdjson_inline error_code visit_one_pass(const uint8_t *buf, size_t len, V &visitor, bool &visitor_failed); /** @private [for benchmarking access] The implementation to use */ std::unique_ptr implementation{}; size_t _capacity{0}; size_t _max_capacity; size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; - std::unique_ptr string_buf{}; + simdjson::internal::allocated_array string_buf{}; + const buffer_allocator *_allocator{nullptr}; #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; @@ -148998,6 +158054,58 @@ class document { * left as is. */ inline void rewind() noexcept; + /** + * Validates the whole document: its structure, every string (escapes included), every + * number, true, false and null, and that nothing follows the root value. Strings are + * checked as get_string() checks them and numbers as get_double() does. The document is + * rewound before and after, so that it can be iterated after a successful validation. + * + * It is faster than iterating through every value, because it walks the tokens directly, + * without creating values, arrays or objects. + * + * @returns SUCCESS if the document is valid, or the error found first. + */ + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + /** + * Walks the whole document once and calls the visitor for each value, in document order. + * Use it to build your own representation of the document (a tree, columns, ...) faster + * than by iterating, as the walk creates no values, arrays or objects. + * + * The visitor provides these methods. Each returns an error_code: anything but SUCCESS stops + * the walk, and visit() returns it. + * + * error_code on_object_start(); + * error_code on_object_end(uint32_t member_count); + * error_code on_array_start(); + * error_code on_array_end(uint32_t element_count); + * error_code on_key(std::string_view key); // before each member value + * error_code on_string(std::string_view value); + * error_code on_int64(int64_t value, const char *raw); // integers that fit an int64_t + * error_code on_uint64(uint64_t value, const char *raw); // larger positive integers + * error_code on_double(double value, const char *raw); + * error_code on_bool(bool value); + * error_code on_null(); + * + * raw points at the number in the document, so that the visitor can tell -0 from 0, for + * example. As with the DOM parser, an integer that does not fit in 64 bits is a BIGINT_ERROR. + * + * A key or a string without escapes is a view into the document: it is valid as long as the + * document's bytes are. A key or a string with escapes is unescaped into the parser: it is + * valid until the document is iterated or visited again, or the parser parses another + * document. + * + * visit() succeeds exactly when the DOM parser does. An error may come after the visitor has + * seen part of the document. The document is rewound before and after the walk, so that it + * can be iterated afterwards. The visitor may throw: the exception goes through visit(), and + * the document must then be rewound before it is used again. + * + * To parse and visit a document in one call, faster on small documents, see parser::visit(). + * + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** * Returns debugging information. */ @@ -149168,6 +158276,9 @@ class document { simdjson_inline value_iterator resume_value_iterator() noexcept; simdjson_inline value_iterator get_root_value_iterator() noexcept; + /** The walk of visit(), between its two rewinds. */ + template + simdjson_warn_unused simdjson_inline error_code visit_root(V &visitor); simdjson_inline simdjson_result start_or_resume_object() noexcept; static simdjson_inline document start(ondemand::json_iterator &&iter) noexcept; @@ -149387,6 +158498,9 @@ struct simdjson_result : public ppc64::implementation simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); simdjson_inline simdjson_result get_array() & noexcept; simdjson_inline simdjson_result get_object() & noexcept; @@ -152674,6 +161788,7 @@ inline std::ostream& operator<<(std::ostream& out, simdjson::simdjson_result #include +#include #if SIMDJSON_STATIC_REFLECTION #include #include @@ -152883,9 +161998,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { SIMDJSON_TRY(v.get(scratch.elements.emplace_back())); release.parsed++; } - out.reserve(release.parsed); - release.complete = true; - for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + if constexpr (std::is_trivially_copyable_v) { + out.assign(scratch.elements.begin(), scratch.elements.end()); + release.complete = true; + } else if (sizeof(value_type) <= 32 && scratch.elements.capacity() / 2 < release.parsed) { + // Hand the buffer over only when it is at least half full, so that out + // does not keep the capacity of an earlier, larger array. Swapping + // large structs is slower than moving them (recipe_book benchmark). + size_t const capacity = scratch.elements.capacity(); + out.swap(scratch.elements); + release.complete = true; + if (capacity * sizeof(value_type) <= (1 << 20)) { scratch.elements.reserve(capacity); } + } else { + out.reserve(release.parsed); + release.complete = true; + for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + } return SUCCESS; } } @@ -153115,7 +162243,11 @@ consteval void append_eligible_fields(std::meta::info type, std::vector(std::meta::substitute(^^flattenable_type, {flattened}))) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member whose type is a structure deserialized member by member", mem); +#else + simdjson::detail::flatten_requires_a_member_deserialized_member_by_member(); +#endif } append_eligible_fields(flattened, prefix, fields); } else { @@ -154471,6 +163603,27 @@ simdjson_warn_unused simdjson_inline simdjson_result value::get_number() return iter.get_number(); } +template +simdjson_warn_unused simdjson_inline error_code value::visit(V &visitor) { + if (!iter.is_at_start()) { return OUT_OF_ORDER_ITERATION; } + json_iterator &json_iter = iter.json_iter(); + const uint8_t *const json = iter.peek_start(); + // The escaped strings of the value go where reading it would put them, so that the string + // buffer has room for them however many times the value is visited. + uint8_t *const string_buf_loc = json_iter._string_buf_loc; + error_code error; + switch (*json) { + case '{': case '[': + error = json_iter.visit_container(visitor, iter.start_position(), size_t(iter.depth() - 1)); + break; + // A scalar value is nested in a container: its parser reads inside the document. + case '"': error = json_iter.visit_string(json, false, visitor); break; + default: error = json_iter.visit_scalar(json, visitor); break; + } + json_iter._string_buf_loc = string_buf_loc; + return error; +} + simdjson_inline std::string_view value::raw_json_token() noexcept { return std::string_view(reinterpret_cast(iter.peek_start()), iter.peek_start_length()); } @@ -154882,6 +164035,12 @@ simdjson_inline simdjson_result::operator bool() noexcep } #endif +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + simdjson_inline simdjson_result simdjson_result::raw_json_token() noexcept { if (error()) { return error(); } return first.raw_json_token(); @@ -154977,6 +164136,124 @@ inline void document::rewind() noexcept { static_cast(iter.rewind()); } +simdjson_warn_unused simdjson_inline error_code document::validate() noexcept { + SIMDJSON_TRY(iter.rewind()); + const bool check_trailing = !iter.streaming(); + const uint8_t first = *iter.peek(); + error_code error; + switch (first) { + case '{': case '[': + error = iter.validate_container(); + break; + case '"': + error = get_root_value_iterator().get_root_string(check_trailing, false).error(); + break; + case 't': case 'f': + error = get_root_value_iterator().get_root_bool(check_trailing).error(); + break; + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && !null_value) { error = N_ATOM_ERROR; } +#if SIMDJSON_ENABLE_NAN_INF + if (error && !get_root_value_iterator().get_root_double(check_trailing).error()) { error = SUCCESS; } +#endif + break; + } + default: + error = get_root_value_iterator().get_root_double(check_trailing).error(); + break; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit(V &visitor) { + SIMDJSON_TRY(iter.rewind()); + const error_code error = visit_root(visitor); + // The strings of the walk stay in the buffer, but an iteration may start from its beginning. + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit_root(V &visitor) { + const bool check_trailing = !iter.streaming(); + const uint8_t *const first = iter.peek(); + const char *const raw = reinterpret_cast(first); + error_code error; + switch (*first) { + case '{': case '[': + return iter.visit_container(visitor, iter.position(), 0); + case '"': { + raw_json_string text; + error = get_root_value_iterator().get_root_raw_json_string(check_trailing).get(text); + if (!error) { return iter.visit_string(first, false, visitor); } + break; + } + case 't': case 'f': { + bool value; + error = get_root_value_iterator().get_root_bool(check_trailing).get(value); + if (!error) { return visitor.on_bool(value); } + break; + } + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && null_value) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + double value; + if (!get_root_value_iterator().get_root_double(check_trailing).get(value)) { return visitor.on_double(value, raw); } +#endif + if (!error) { error = N_ATOM_ERROR; } + break; + } + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + number value; + error = get_root_value_iterator().get_root_number(check_trailing).get(value); + if (!error) { return json_iterator::visit_number(value, raw, visitor); } + break; + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': { + double value; + error = get_root_value_iterator().get_root_double(check_trailing).get(value); + if (!error) { return visitor.on_double(value, raw); } + return error == TRAILING_CONTENT ? error : TAPE_ERROR; + } +#endif + default: + return TAPE_ERROR; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (*first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + return error; +} + inline std::string document::to_debug_string() noexcept { return iter.to_string(); } @@ -155531,6 +164808,16 @@ simdjson_inline error_code simdjson_result::rewind() first.rewind(); return SUCCESS; } +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + +simdjson_warn_unused simdjson_inline error_code simdjson_result::validate() noexcept { + if (error()) { return error(); } + return first.validate(); +} simdjson_inline simdjson_result simdjson_result::begin() & noexcept { if (error()) { return error(); } return first.begin(); @@ -156601,6 +165888,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } worker->start_thread(); @@ -156854,6 +166142,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch @@ -156869,6 +166160,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -157210,6 +166504,8 @@ simdjson_inline simdjson_result simdjson_result= 8; src += 8, len -= 8) { + std::memcpy(&word, src, sizeof(word)); + word ^= BACKSLASHES; + if ((word - ONES) & ~word & HIGHS) { return true; } + } + uint64_t keep; + std::memcpy(&keep, KEEP + 8 - len, sizeof(keep)); + std::memcpy(&word, src, sizeof(word)); + word = (word ^ BACKSLASHES) | ~keep; + return ((word - ONES) & ~word & HIGHS) != 0; +} + +simdjson_warn_unused simdjson_never_inline error_code json_iterator::validate_container() noexcept { + const uint8_t *const json = token.buf; + token_position pos = token.position(); + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // One bit per depth tells whether the container at that depth is an array. Deeper than + // the fixed stack allows, the bits move to the heap. + uint64_t fixed_stack[16]{}; + std::unique_ptr heap_stack; + uint64_t *is_array = fixed_stack; + size_t depth = 0; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VALIDATE_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VALIDATE_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': goto scalar_string; + default: goto scalar; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. Its bit may then + // be at max_depth, which the stack has room for. + if (++depth >= max_depth && (pos == end || json[*pos] != c + 2)) { return DEPTH_ERROR; } + // The bits move once: the next time this depth is reached, the heap holds the current + // bits and the fixed stack holds stale ones. + if (depth == sizeof(fixed_stack) * 8 && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint64_t[max_depth / 64 + 1]()); + if (!heap_stack) { return MEMALLOC; } + std::memcpy(heap_stack.get(), fixed_stack, sizeof(fixed_stack)); + is_array = heap_stack.get(); + } + if (c == '[') { + is_array[depth / 64] |= uint64_t(1) << (depth % 64); + SIMDJSON_VALIDATE_NEXT(); + if (c == ']') { goto container_end; } + goto value; + } + is_array[depth / 64] &= ~(uint64_t(1) << (depth % 64)); + SIMDJSON_VALIDATE_NEXT(); + if (c == '}') { goto container_end; } + goto key; + +key: + if (c != '"') { return TAPE_ERROR; } + // A string is valid once stage 1 has accepted the document, unless it holds an escape. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + SIMDJSON_VALIDATE_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VALIDATE_NEXT(); + goto value; + +scalar_string: + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + goto value_end; + +scalar: + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + break; + default: + return TAPE_ERROR; + } + // The scalar is not the last token, so the parsers read inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + switch (c) { + case 't': if (!atomparsing::is_valid_true_atom(json + index)) { return T_ATOM_ERROR; } break; + case 'f': if (!atomparsing::is_valid_false_atom(json + index)) { return F_ATOM_ERROR; } break; + case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (!atomparsing::is_valid_null_atom(json + index) && !atomparsing::is_valid_nan_atom(json + index)) { return N_ATOM_ERROR; } +#else + if (!atomparsing::is_valid_null_atom(json + index)) { return N_ATOM_ERROR; } +#endif + break; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': if (!atomparsing::is_valid_nan_atom(json + index)) { return TAPE_ERROR; } break; + case 'i': case 'I': if (!atomparsing::is_valid_inf_atom(json + index)) { return TAPE_ERROR; } break; +#endif + default: + if (numberparsing::parse_double(json + index).error()) { return NUMBER_ERROR; } + break; + } + +value_end: + SIMDJSON_VALIDATE_NEXT(); + if (c == ',') { + SIMDJSON_VALIDATE_NEXT(); + if (is_array[depth / 64] & (uint64_t(1) << (depth % 64))) { goto value; } + goto key; + } + if (c != (is_array[depth / 64] & (uint64_t(1) << (depth % 64)) ? ']' : '}')) { return TAPE_ERROR; } + +container_end: + if (--depth > 0) { goto value_end; } +#undef SIMDJSON_VALIDATE_NEXT + if (!streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_number(const number &value, const char *raw, V &visitor) { + switch (value.get_number_type()) { + case number_type::signed_integer: return visitor.on_int64(value.get_int64(), raw); + case number_type::unsigned_integer: return visitor.on_uint64(value.get_uint64(), raw); + case number_type::floating_point_number: return visitor.on_double(value.get_double(), raw); + default: return BIGINT_ERROR; + } +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_string(const uint8_t *quote, bool key, V &visitor) { + const uint8_t *const start = quote + 1; + // A string without escapes is passed as it is in the document. + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (const uint8_t *src = start;; src += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(src, scratch); + if (bs_quote.has_quote_first()) { + std::string_view text(reinterpret_cast(start), size_t(src - start) + size_t(bs_quote.quote_index())); + return key ? visitor.on_key(text) : visitor.on_string(text); + } + if (bs_quote.has_backslash()) { break; } + } + uint8_t *const end = parser->implementation->parse_string(start, _string_buf_loc, false); + if (!end) { return STRING_ERROR; } + std::string_view text(reinterpret_cast(_string_buf_loc), size_t(end - _string_buf_loc)); + _string_buf_loc = end; + return key ? visitor.on_key(text) : visitor.on_string(text); +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_scalar(const uint8_t *src, V &visitor) { + switch (*src) { + case 't': return atomparsing::is_valid_true_atom(src) ? visitor.on_bool(true) : T_ATOM_ERROR; + case 'f': return atomparsing::is_valid_false_atom(src) ? visitor.on_bool(false) : F_ATOM_ERROR; + case 'n': + if (atomparsing::is_valid_null_atom(src)) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } +#endif + return N_ATOM_ERROR; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + number value; + SIMDJSON_TRY(numberparsing::parse_number(src, value)); + return visit_number(value, reinterpret_cast(src), visitor); + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } + return TAPE_ERROR; + case 'i': case 'I': + if (atomparsing::is_valid_inf_atom(src)) { return visitor.on_double(std::numeric_limits::infinity(), reinterpret_cast(src)); } + return TAPE_ERROR; +#endif + default: + return TAPE_ERROR; + } +} + +template +simdjson_warn_unused error_code json_iterator::visit_container(V &visitor, token_position start, size_t parent_depth) { + const uint8_t *const json = token.buf; + token_position pos = start; + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // For each open container, the number of its elements so far, with the top bit set for an + // array. Deeper than the fixed stack allows, the stack moves to the heap. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + constexpr size_t FIXED_DEPTH = 64; + uint32_t fixed_stack[FIXED_DEPTH]; + std::unique_ptr heap_stack; + uint32_t *stack = fixed_stack; + size_t depth = parent_depth; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VISIT_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VISIT_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': + // A string is not the last token, so that its closing quote is inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, false, visitor)); + goto value_end; + default: + // The scalar is not the last token, so the parsers read inside the document. + if (simdjson_unlikely(pos == end)) { + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + return INCOMPLETE_ARRAY_OR_OBJECT; + default: + return TAPE_ERROR; + } + } + SIMDJSON_TRY(visit_scalar(json + index, visitor)); + goto value_end; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. + if (pos != end && json[*pos] == c + 2) { + pos++; + if (c == '[') { + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_TRY(visitor.on_array_end(0)); + } else { + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_TRY(visitor.on_object_end(0)); + } + if (depth == parent_depth) { goto document_end; } + goto value_end; + } + if (++depth >= max_depth) { return DEPTH_ERROR; } + // Copy the fixed stack once. A later container at this depth must keep the + // counts already stored on the heap. + if (depth >= FIXED_DEPTH && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint32_t[max_depth]); + if (!heap_stack) { return MEMALLOC; } + // Only the slots past the parent were written. + if (parent_depth + 1 < FIXED_DEPTH) { + std::memcpy(heap_stack.get() + parent_depth + 1, fixed_stack + parent_depth + 1, (FIXED_DEPTH - parent_depth - 1) * sizeof(fixed_stack[0])); + } + stack = heap_stack.get(); + } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_VISIT_NEXT(); + goto value; + } + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_VISIT_NEXT(); + +key: + if (c != '"') { return TAPE_ERROR; } + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, true, visitor)); + SIMDJSON_VISIT_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VISIT_NEXT(); + goto value; + +value_end: + SIMDJSON_VISIT_NEXT(); + if (c == ',') { + stack[depth]++; + SIMDJSON_VISIT_NEXT(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_object_end(stack[depth])); + } + if (--depth > parent_depth) { goto value_end; } + +document_end: +#undef SIMDJSON_VISIT_NEXT + if (parent_depth == 0 && !streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + simdjson_inline bool json_iterator::at_root() const noexcept { return position() == root_position(); } @@ -157850,10 +167475,20 @@ simdjson_warn_unused simdjson_inline bool json_iterator::copy_to_buffer(const ui // peek_root_length() stops at the next structural index. Stage 1 omits the // comma or RS (0x1E) that separates stream documents, so that byte and the // whitespace around it remain in the span. RS is not a valid number finisher. + // Outside of a stream, the comma and RS are not separators: some kernels + // keep RS in the scalar token, and dropping it would accept "1\x1e". while (max_len > 0) { const uint8_t last = json[max_len - 1]; + // iterate_allow_incomplete_json() reuses _streaming, so a root scalar + // there is not a document_stream. +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + const bool separator = _streaming && !_allow_incomplete_json && + (last == ',' || last == 0x1E); +#else + const bool separator = _streaming && (last == ',' || last == 0x1E); +#endif if (last != ' ' && last != '\t' && last != '\n' && last != '\r' && - last != ',' && last != 0x1E) { + !separator) { break; } max_len--; @@ -159283,22 +168918,22 @@ simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capa return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - std::unique_ptr new_string_buf(new (std::nothrow) uint8_t[string_capacity]); - if (!new_string_buf) { return MEMALLOC; } + simdjson::internal::allocated_array new_string_buf; + if (!new_string_buf.allocate(string_capacity, _allocator)) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr new_start_positions(new (std::nothrow) token_position[new_max_depth]); if (!new_start_positions) { return MEMALLOC; } #endif - if (implementation) { - error_code err = implementation->allocate(new_capacity, new_max_depth); - if (err) { return err; } - } else { - error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, new_max_depth, implementation); if (err) { implementation.reset(); return err; } } + implementation->allocator = _allocator; + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } string_buf = std::move(new_string_buf); #if SIMDJSON_DEVELOPMENT_CHECKS start_positions = std::move(new_start_positions); @@ -159327,9 +168962,42 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iterate(p // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return document::start({ reinterpret_cast(json.data()), this }); } +// Removes from the structural indexes each comma that follows a value and +// precedes a closing bracket, so that the iterator never sees it. The entries +// past the last index (stage 1 keeps up to three there) move with the others. +#if SIMDJSON_ALLOW_TRAILING_COMMAS +simdjson_inline void parser::drop_trailing_commas(const uint8_t *buf) noexcept { + uint32_t *indexes = implementation->structural_indexes.get(); + const uint32_t n = implementation->n_structural_indexes; + uint32_t kept = 0; + uint8_t previous = '['; + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = buf[indexes[i]]; + if (c == ',' && i + 1 < n && previous != '[' && previous != '{' && previous != ',' && previous != ':') { + const uint8_t next = buf[indexes[i + 1]]; + if (next == ']' || next == '}') { + previous = c; + continue; + } + } + indexes[kept++] = indexes[i]; + previous = c; + } + if (kept != n) { + indexes[kept] = indexes[n]; + indexes[kept + 1] = indexes[n + 1]; + indexes[kept + 2] = indexes[n + 2]; + implementation->n_structural_indexes = kept; + } +} +#endif // SIMDJSON_ALLOW_TRAILING_COMMAS + #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_warn_unused simdjson_inline simdjson_result parser::iterate_allow_incomplete_json(padded_string_view json) & noexcept { if (!json.has_sufficient_padding()) { return INSUFFICIENT_PADDING; } @@ -159433,9 +169101,210 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iter // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return json_iterator(reinterpret_cast(json.data()), this); } +namespace { +struct ignoring_visitor { + simdjson_inline error_code on_object_start() { return SUCCESS; } + simdjson_inline error_code on_object_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_array_start() { return SUCCESS; } + simdjson_inline error_code on_array_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_key(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_string(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_int64(int64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_uint64(uint64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_double(double, const char *) { return SUCCESS; } + simdjson_inline error_code on_bool(bool) { return SUCCESS; } + simdjson_inline error_code on_null() { return SUCCESS; } +}; +} // unnamed namespace + +template +simdjson_warn_unused simdjson_inline error_code parser::visit(padded_string_view json, V &visitor) & { +#if !SIMDJSON_ENABLE_NAN_INF && !SIMDJSON_ALLOW_TRAILING_COMMAS + if (json.length() <= MAX_ONE_PASS_VISIT && json.has_sufficient_padding()) { + if (capacity() < json.length() || !string_buf) { + SIMDJSON_TRY( allocate(json.length(), max_depth()) ); + } + bool visitor_failed = false; + const error_code error = visit_one_pass(reinterpret_cast(json.data()), json.length(), visitor, visitor_failed); + if (error != UNINITIALIZED) { + if (error != TAPE_ERROR || visitor_failed) { return error; } + // The visitor has already seen part of the document: the regular walk only finds the + // error code, and never calls the visitor a second time. + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + ignoring_visitor ignoring; + const error_code regular_error = doc.visit(ignoring); + return regular_error ? regular_error : TAPE_ERROR; + } + } +#endif + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + return doc.visit(visitor); +} + +// A single pass over the bytes, for small documents. The root must be an array or an object, and +// the last byte that is not whitespace must be ] or }: before it, runs of whitespace, digits or +// atoms stop without a bound check. Only a closing bracket or a string may reach the end. +template +simdjson_warn_unused simdjson_inline error_code parser::visit_one_pass(const uint8_t *const buf, const size_t len, V &visitor, bool &visitor_failed) { + const auto is_whitespace = [](uint8_t c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; + if (len == 0 || len > MAX_ONE_PASS_VISIT) { return UNINITIALIZED; } + const uint8_t *p = buf; + const uint8_t *last = buf + len - 1; + while (p < last && is_whitespace(*p)) { p++; } + while (last > p && is_whitespace(*last)) { last--; } + if ((*p != '{' && *p != '[') || (*last != '}' && *last != ']')) { return UNINITIALIZED; } + const uint8_t *const end = last + 1; + uint8_t *dst = string_buf.get(); + bool non_ascii = false; + // For each open container, the number of its elements so far, with the top bit set for an + // array. Each container opens at a distinct byte before the last one, so that the depth stays + // below MAX_ONE_PASS_VISIT. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + uint32_t stack[MAX_ONE_PASS_VISIT]; + size_t depth = 0; + uint8_t c = *p; + +#define SIMDJSON_ONE_PASS_CALL(EXPR) \ + do { \ + const error_code one_pass_error = (EXPR); \ + if (simdjson_unlikely(one_pass_error != SUCCESS)) { visitor_failed = true; return one_pass_error; } \ + } while (0) +#define SIMDJSON_ONE_PASS_WHITESPACE() while (is_whitespace(*p)) { p++; } +// The string at p, which is left past the closing quote. +#define SIMDJSON_ONE_PASS_STRING(METHOD) \ + do { \ + const uint8_t *const start = ++p; \ + bool escaped = false; \ + for (;; p++) { \ + if (simdjson_unlikely(p >= end)) { return TAPE_ERROR; } \ + if (*p == '"') { break; } \ + if (*p == '\\') { \ + escaped = true; \ + p++; \ + } else if (simdjson_unlikely(*p < 0x20)) { \ + return TAPE_ERROR; \ + } else if (*p >= 0x80) { \ + non_ascii = true; \ + } \ + } \ + std::string_view text(reinterpret_cast(start), size_t(p - start)); \ + p++; \ + if (escaped) { \ + uint8_t *const unescaped_end = implementation->parse_string(start, dst, false); \ + if (unescaped_end == nullptr) { return TAPE_ERROR; } \ + text = std::string_view(reinterpret_cast(dst), size_t(unescaped_end - dst)); \ + dst = unescaped_end; \ + } \ + SIMDJSON_ONE_PASS_CALL(visitor.METHOD(text)); \ + } while (0) + + goto container_start; + +value: + switch (*p) { + case '{': case '[': + c = *p; + goto container_start; + case '"': + SIMDJSON_ONE_PASS_STRING(on_string); + goto value_end; + case 't': + if (!atomparsing::is_valid_true_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(true)); + p += 4; + goto value_end; + case 'f': + if (!atomparsing::is_valid_false_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(false)); + p += 5; + goto value_end; + case 'n': + if (!atomparsing::is_valid_null_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_null()); + p += 4; + goto value_end; + default: { + number value; + if (numberparsing::parse_number(p, value) != SUCCESS) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(json_iterator::visit_number(value, reinterpret_cast(p), visitor)); + while (jsoncharutils::is_not_structural_or_whitespace(*p)) { p++; } + goto value_end; + } + } + +container_start: + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + // As in DOM, an empty container does not count toward the maximal depth. + if (*p == c + 2) { + p++; + if (c == '[') { + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(0)); + } else { + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(0)); + } + if (depth == 0) { goto document_end; } + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + if (++depth >= max_depth()) { return TAPE_ERROR; } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + goto value; + } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + +key: + if (*p != '"') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_STRING(on_key); + SIMDJSON_ONE_PASS_WHITESPACE(); + if (*p != ':') { return TAPE_ERROR; } + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + goto value; + +value_end: + SIMDJSON_ONE_PASS_WHITESPACE(); + c = *p++; + if (c == ',') { + stack[depth]++; + SIMDJSON_ONE_PASS_WHITESPACE(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(stack[depth])); + } + if (--depth > 0) { + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + +document_end: +#undef SIMDJSON_ONE_PASS_CALL +#undef SIMDJSON_ONE_PASS_WHITESPACE +#undef SIMDJSON_ONE_PASS_STRING + if (p != end) { return TAPE_ERROR; } + if (non_ascii && !simdjson::validate_utf8(reinterpret_cast(buf), len)) { return TAPE_ERROR; } + return SUCCESS; +} + inline simdjson_result parser::iterate_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept { if(batch_size < MINIMAL_BATCH_SIZE) { batch_size = MINIMAL_BATCH_SIZE; } if((len >= 3) && (std::memcmp(buf, "\xEF\xBB\xBF", 3) == 0)) { @@ -159553,6 +169422,13 @@ simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return _max_depth; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} + simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept { if(max_capacity > dom::MINIMAL_DOCUMENT_CAPACITY) { _max_capacity = max_capacity; @@ -160072,13 +169948,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_objec _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing } at end"); } - // If the last character is } *and* the first gibberish character is also '}' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is } *and* the first gibberish character is '}', ']' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == '}') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed object. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -160482,13 +170360,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_array _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing ] at end"); } - // If the last character is ] *and* the first gibberish character is also ']' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is ] *and* the first gibberish character is ']', '}' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == ']') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed array. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -160658,7 +170538,7 @@ simdjson_inline simdjson_result value_iterator::get_root_num // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -160682,7 +170562,7 @@ simdjson_inline simdjson_result value_iterator::get_root_number(bool che // number: -0.e-308. // NOTE: the current approach doesn't work for very big integer numbers containing more than 1074 digits. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -160764,7 +170644,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::g simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer tmpbuf[20+1] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+1)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 20 characters"); @@ -160781,7 +170661,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::ge simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64_in_string(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer tmpbuf[20+2] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+2)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 22 characters"); @@ -160802,7 +170682,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -160824,7 +170704,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -160846,7 +170726,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ // digits that matter is smaller for binary32, but the JSON document may still // spell out a long number that we must parse (and round) faithfully. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -160865,7 +170745,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ auto max_len = peek_root_length(); auto json = peek_root_scalar("float"); // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -161203,6 +171083,9 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '"': return json_type::string; case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } +#endif return json_type::null; case 't': case 'f': return json_type::boolean; @@ -161210,6 +171093,14 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return json_type::number; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; + case 'I': case 'i': + if (atomparsing::is_valid_inf_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; +#endif default: return json_type::unknown; } @@ -162517,6 +172408,7 @@ simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -162711,6 +172603,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -162936,6 +172846,7 @@ simdjson_inline long long int count_ones(uint64_t input_num) { /* amalgamation skipped (editor-only): #include "simdjson/westmere/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/westmere/bitmanipulation.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/simdprune_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/partial_load.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ namespace simdjson { @@ -163130,6 +173041,24 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline __m128i load_partial_16(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + if (size_t(ptr - begin) + n >= 16) { + const __m128i window = _mm_loadu_si128(reinterpret_cast(ptr + n - 16)); + const __m128i shuffle = _mm_loadu_si128(reinterpret_cast(internal::shift_tail_mask + 16 - n)); + // _mm_shuffle_epi8 zeroes the bytes whose index has the high bit set. + const __m128i filler = _mm_and_si128(_mm_cmplt_epi8(shuffle, _mm_setzero_si128()), _mm_set1_epi8(char(fill))); + return _mm_or_si128(_mm_shuffle_epi8(window, shuffle), filler); + } + uint64_t lo, hi; + internal::load_small_words(ptr, n, fill, lo, hi); + return _mm_set_epi64x(int64_t(hi), int64_t(lo)); + } + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [begin, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + return load_partial_16(ptr, n, begin, fill); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -164753,6 +174682,23 @@ class value { */ simdjson_inline std::string_view raw_json_token() noexcept; + /** + * Calls the visitor for this value and everything in it, as document::visit() does for a + * whole document, for example after navigating to a field: + * + * auto error = doc["payload"].visit(visitor); + * + * The value must not have been read. The walk does not move the iterator: to go on, read the + * value or the next field or element as usual. A string with escapes is valid until you read + * the document further or visit again. The maximal depth counts from the root of the document. + * A value at the root also fails if anything follows it. + * + * @returns SUCCESS, OUT_OF_ORDER_ITERATION if the value has been read, the first error found + * in the value, or the first error the visitor returns. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); + /** * Get a string_view pointing at this value in the JSON document. * If this element is an array or an object, it consumes the array or the object @@ -165070,6 +175016,8 @@ struct simdjson_result : public westmere::implementat /** @copydoc simdjson_inline std::string_view value::raw_json_token() const noexcept */ simdjson_inline simdjson_result raw_json_token() noexcept; simdjson_inline simdjson_result raw_json() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** @copydoc simdjson_inline simdjson_result current_location() noexcept */ simdjson_inline simdjson_result current_location() noexcept; @@ -165415,6 +175363,29 @@ class json_iterator { simdjson_inline error_code out_of_place_error() noexcept; /** Tells whether the string before pos, followed by a colon, is a key. */ static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; + /** + * Validates the array or object at the current position and everything in it, without + * recursion. Outside of streaming mode, it also checks that nothing follows it. It does + * not move the iterator. + */ + simdjson_warn_unused error_code validate_container() noexcept; + static simdjson_inline bool has_backslash(const uint8_t *src, size_t len) noexcept; + /** + * Calls the visitor for the array or object at the start position and everything in it, + * without recursion (see document::visit()). The container is at depth parent_depth + 1. At + * the root (parent_depth == 0) and outside of streaming mode, it also checks that nothing + * follows it. It does not move the iterator. Escaped strings are copied into the string + * buffer. + */ + template + simdjson_warn_unused error_code visit_container(V &visitor, token_position start, size_t parent_depth); + template + simdjson_warn_unused simdjson_inline error_code visit_string(const uint8_t *quote, bool key, V &visitor); + template + simdjson_warn_unused simdjson_inline error_code visit_scalar(const uint8_t *src, V &visitor); + /** Calls the visitor for a number that numberparsing::parse_number accepted. */ + template + static simdjson_warn_unused simdjson_inline error_code visit_number(const number &value, const char *raw, V &visitor); /** * Tell whether the iterator is still at the start @@ -165604,7 +175575,8 @@ class json_iterator { /** * Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with * N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero. - * Trailing whitespace, commas, and record separators (0x1E) do not count toward max_len. + * Trailing whitespace does not count toward max_len. A comma or record + * separator (0x1E) is ignored only for a document stream. * The buffer (tmpbuf) is padded with space characters. */ simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept; @@ -166300,6 +176272,33 @@ class parser { */ simdjson_warn_unused simdjson_result iterate_raw(padded_string_view json) & noexcept; + /** + * Parses the document and walks it once with the visitor: the same as iterate() followed by + * document::visit(), with the same values and, when the visitor returns SUCCESS, the same + * error code, but faster on small documents. + * + * counting_visitor visitor; + * auto error = parser.visit(R"({"stars":[1,2,3]})"_padded, visitor); + * + * A document of at most MAX_ONE_PASS_VISIT bytes whose root is an object or an array is read in + * a single pass, without the structural index that iterate() builds. Some checks, such as the + * UTF-8 validation, then come at the end of the walk: on an invalid document, the visitor may + * have seen part or all of it before visit() returns the error code of document::visit(), and + * an error returned by the visitor may come first. With SIMDJSON_ENABLE_NAN_INF or + * SIMDJSON_ALLOW_TRAILING_COMMAS, there is no one-pass walk. + * + * See document::visit() for the methods of the visitor and the lifetime of the strings. + * + * @param json The JSON to parse, with at least SIMDJSON_PADDING bytes after it. + * @param visitor The visitor. + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(padded_string_view json, V &visitor) &; + /** Documents of at most this many bytes may be visited in one pass, see visit(). */ + static constexpr size_t MAX_ONE_PASS_VISIT = 32; + /** * Parse a buffer containing many JSON documents. @@ -166458,6 +176457,20 @@ class parser { */ simdjson_pure simdjson_inline size_t max_depth() const noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the string buffer and the structural indexes) through a buffer_allocator. + * nullptr, the default, uses new[]. The allocator must outlive the parser. + * + * Buffers that the parser already holds keep the allocator that allocated + * them until the parser grows them, so set the allocator before the first + * document or the first call to allocate(). A failed allocation makes the + * parser return MEMALLOC and leaves its buffers as they were. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + /** * Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length * and `max_depth` depth. @@ -166567,17 +176580,27 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr& get_threadlocal_parser_if_exists(); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + simdjson_inline void drop_trailing_commas(const uint8_t *buf) noexcept; +#endif #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** + * The one-pass walk of visit(). Returns UNINITIALIZED when it does not handle the document, + * and TAPE_ERROR when the document is invalid. visitor_failed tells an error of the visitor. + */ + template + simdjson_warn_unused simdjson_inline error_code visit_one_pass(const uint8_t *buf, size_t len, V &visitor, bool &visitor_failed); /** @private [for benchmarking access] The implementation to use */ std::unique_ptr implementation{}; size_t _capacity{0}; size_t _max_capacity; size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; - std::unique_ptr string_buf{}; + simdjson::internal::allocated_array string_buf{}; + const buffer_allocator *_allocator{nullptr}; #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; @@ -167835,6 +177858,58 @@ class document { * left as is. */ inline void rewind() noexcept; + /** + * Validates the whole document: its structure, every string (escapes included), every + * number, true, false and null, and that nothing follows the root value. Strings are + * checked as get_string() checks them and numbers as get_double() does. The document is + * rewound before and after, so that it can be iterated after a successful validation. + * + * It is faster than iterating through every value, because it walks the tokens directly, + * without creating values, arrays or objects. + * + * @returns SUCCESS if the document is valid, or the error found first. + */ + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + /** + * Walks the whole document once and calls the visitor for each value, in document order. + * Use it to build your own representation of the document (a tree, columns, ...) faster + * than by iterating, as the walk creates no values, arrays or objects. + * + * The visitor provides these methods. Each returns an error_code: anything but SUCCESS stops + * the walk, and visit() returns it. + * + * error_code on_object_start(); + * error_code on_object_end(uint32_t member_count); + * error_code on_array_start(); + * error_code on_array_end(uint32_t element_count); + * error_code on_key(std::string_view key); // before each member value + * error_code on_string(std::string_view value); + * error_code on_int64(int64_t value, const char *raw); // integers that fit an int64_t + * error_code on_uint64(uint64_t value, const char *raw); // larger positive integers + * error_code on_double(double value, const char *raw); + * error_code on_bool(bool value); + * error_code on_null(); + * + * raw points at the number in the document, so that the visitor can tell -0 from 0, for + * example. As with the DOM parser, an integer that does not fit in 64 bits is a BIGINT_ERROR. + * + * A key or a string without escapes is a view into the document: it is valid as long as the + * document's bytes are. A key or a string with escapes is unescaped into the parser: it is + * valid until the document is iterated or visited again, or the parser parses another + * document. + * + * visit() succeeds exactly when the DOM parser does. An error may come after the visitor has + * seen part of the document. The document is rewound before and after the walk, so that it + * can be iterated afterwards. The visitor may throw: the exception goes through visit(), and + * the document must then be rewound before it is used again. + * + * To parse and visit a document in one call, faster on small documents, see parser::visit(). + * + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** * Returns debugging information. */ @@ -168005,6 +178080,9 @@ class document { simdjson_inline value_iterator resume_value_iterator() noexcept; simdjson_inline value_iterator get_root_value_iterator() noexcept; + /** The walk of visit(), between its two rewinds. */ + template + simdjson_warn_unused simdjson_inline error_code visit_root(V &visitor); simdjson_inline simdjson_result start_or_resume_object() noexcept; static simdjson_inline document start(ondemand::json_iterator &&iter) noexcept; @@ -168224,6 +178302,9 @@ struct simdjson_result : public westmere::implemen simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); simdjson_inline simdjson_result get_array() & noexcept; simdjson_inline simdjson_result get_object() & noexcept; @@ -171511,6 +181592,7 @@ inline std::ostream& operator<<(std::ostream& out, simdjson::simdjson_result #include +#include #if SIMDJSON_STATIC_REFLECTION #include #include @@ -171720,9 +181802,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { SIMDJSON_TRY(v.get(scratch.elements.emplace_back())); release.parsed++; } - out.reserve(release.parsed); - release.complete = true; - for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + if constexpr (std::is_trivially_copyable_v) { + out.assign(scratch.elements.begin(), scratch.elements.end()); + release.complete = true; + } else if (sizeof(value_type) <= 32 && scratch.elements.capacity() / 2 < release.parsed) { + // Hand the buffer over only when it is at least half full, so that out + // does not keep the capacity of an earlier, larger array. Swapping + // large structs is slower than moving them (recipe_book benchmark). + size_t const capacity = scratch.elements.capacity(); + out.swap(scratch.elements); + release.complete = true; + if (capacity * sizeof(value_type) <= (1 << 20)) { scratch.elements.reserve(capacity); } + } else { + out.reserve(release.parsed); + release.complete = true; + for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + } return SUCCESS; } } @@ -171952,7 +182047,11 @@ consteval void append_eligible_fields(std::meta::info type, std::vector(std::meta::substitute(^^flattenable_type, {flattened}))) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member whose type is a structure deserialized member by member", mem); +#else + simdjson::detail::flatten_requires_a_member_deserialized_member_by_member(); +#endif } append_eligible_fields(flattened, prefix, fields); } else { @@ -173308,6 +183407,27 @@ simdjson_warn_unused simdjson_inline simdjson_result value::get_number() return iter.get_number(); } +template +simdjson_warn_unused simdjson_inline error_code value::visit(V &visitor) { + if (!iter.is_at_start()) { return OUT_OF_ORDER_ITERATION; } + json_iterator &json_iter = iter.json_iter(); + const uint8_t *const json = iter.peek_start(); + // The escaped strings of the value go where reading it would put them, so that the string + // buffer has room for them however many times the value is visited. + uint8_t *const string_buf_loc = json_iter._string_buf_loc; + error_code error; + switch (*json) { + case '{': case '[': + error = json_iter.visit_container(visitor, iter.start_position(), size_t(iter.depth() - 1)); + break; + // A scalar value is nested in a container: its parser reads inside the document. + case '"': error = json_iter.visit_string(json, false, visitor); break; + default: error = json_iter.visit_scalar(json, visitor); break; + } + json_iter._string_buf_loc = string_buf_loc; + return error; +} + simdjson_inline std::string_view value::raw_json_token() noexcept { return std::string_view(reinterpret_cast(iter.peek_start()), iter.peek_start_length()); } @@ -173719,6 +183839,12 @@ simdjson_inline simdjson_result::operator bool() noex } #endif +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + simdjson_inline simdjson_result simdjson_result::raw_json_token() noexcept { if (error()) { return error(); } return first.raw_json_token(); @@ -173814,6 +183940,124 @@ inline void document::rewind() noexcept { static_cast(iter.rewind()); } +simdjson_warn_unused simdjson_inline error_code document::validate() noexcept { + SIMDJSON_TRY(iter.rewind()); + const bool check_trailing = !iter.streaming(); + const uint8_t first = *iter.peek(); + error_code error; + switch (first) { + case '{': case '[': + error = iter.validate_container(); + break; + case '"': + error = get_root_value_iterator().get_root_string(check_trailing, false).error(); + break; + case 't': case 'f': + error = get_root_value_iterator().get_root_bool(check_trailing).error(); + break; + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && !null_value) { error = N_ATOM_ERROR; } +#if SIMDJSON_ENABLE_NAN_INF + if (error && !get_root_value_iterator().get_root_double(check_trailing).error()) { error = SUCCESS; } +#endif + break; + } + default: + error = get_root_value_iterator().get_root_double(check_trailing).error(); + break; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit(V &visitor) { + SIMDJSON_TRY(iter.rewind()); + const error_code error = visit_root(visitor); + // The strings of the walk stay in the buffer, but an iteration may start from its beginning. + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit_root(V &visitor) { + const bool check_trailing = !iter.streaming(); + const uint8_t *const first = iter.peek(); + const char *const raw = reinterpret_cast(first); + error_code error; + switch (*first) { + case '{': case '[': + return iter.visit_container(visitor, iter.position(), 0); + case '"': { + raw_json_string text; + error = get_root_value_iterator().get_root_raw_json_string(check_trailing).get(text); + if (!error) { return iter.visit_string(first, false, visitor); } + break; + } + case 't': case 'f': { + bool value; + error = get_root_value_iterator().get_root_bool(check_trailing).get(value); + if (!error) { return visitor.on_bool(value); } + break; + } + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && null_value) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + double value; + if (!get_root_value_iterator().get_root_double(check_trailing).get(value)) { return visitor.on_double(value, raw); } +#endif + if (!error) { error = N_ATOM_ERROR; } + break; + } + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + number value; + error = get_root_value_iterator().get_root_number(check_trailing).get(value); + if (!error) { return json_iterator::visit_number(value, raw, visitor); } + break; + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': { + double value; + error = get_root_value_iterator().get_root_double(check_trailing).get(value); + if (!error) { return visitor.on_double(value, raw); } + return error == TRAILING_CONTENT ? error : TAPE_ERROR; + } +#endif + default: + return TAPE_ERROR; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (*first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + return error; +} + inline std::string document::to_debug_string() noexcept { return iter.to_string(); } @@ -174368,6 +184612,16 @@ simdjson_inline error_code simdjson_result::rewind first.rewind(); return SUCCESS; } +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + +simdjson_warn_unused simdjson_inline error_code simdjson_result::validate() noexcept { + if (error()) { return error(); } + return first.validate(); +} simdjson_inline simdjson_result simdjson_result::begin() & noexcept { if (error()) { return error(); } return first.begin(); @@ -175438,6 +185692,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } worker->start_thread(); @@ -175691,6 +185946,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch @@ -175706,6 +185964,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -176047,6 +186308,8 @@ simdjson_inline simdjson_result simdjson_result= 8; src += 8, len -= 8) { + std::memcpy(&word, src, sizeof(word)); + word ^= BACKSLASHES; + if ((word - ONES) & ~word & HIGHS) { return true; } + } + uint64_t keep; + std::memcpy(&keep, KEEP + 8 - len, sizeof(keep)); + std::memcpy(&word, src, sizeof(word)); + word = (word ^ BACKSLASHES) | ~keep; + return ((word - ONES) & ~word & HIGHS) != 0; +} + +simdjson_warn_unused simdjson_never_inline error_code json_iterator::validate_container() noexcept { + const uint8_t *const json = token.buf; + token_position pos = token.position(); + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // One bit per depth tells whether the container at that depth is an array. Deeper than + // the fixed stack allows, the bits move to the heap. + uint64_t fixed_stack[16]{}; + std::unique_ptr heap_stack; + uint64_t *is_array = fixed_stack; + size_t depth = 0; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VALIDATE_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VALIDATE_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': goto scalar_string; + default: goto scalar; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. Its bit may then + // be at max_depth, which the stack has room for. + if (++depth >= max_depth && (pos == end || json[*pos] != c + 2)) { return DEPTH_ERROR; } + // The bits move once: the next time this depth is reached, the heap holds the current + // bits and the fixed stack holds stale ones. + if (depth == sizeof(fixed_stack) * 8 && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint64_t[max_depth / 64 + 1]()); + if (!heap_stack) { return MEMALLOC; } + std::memcpy(heap_stack.get(), fixed_stack, sizeof(fixed_stack)); + is_array = heap_stack.get(); + } + if (c == '[') { + is_array[depth / 64] |= uint64_t(1) << (depth % 64); + SIMDJSON_VALIDATE_NEXT(); + if (c == ']') { goto container_end; } + goto value; + } + is_array[depth / 64] &= ~(uint64_t(1) << (depth % 64)); + SIMDJSON_VALIDATE_NEXT(); + if (c == '}') { goto container_end; } + goto key; + +key: + if (c != '"') { return TAPE_ERROR; } + // A string is valid once stage 1 has accepted the document, unless it holds an escape. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + SIMDJSON_VALIDATE_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VALIDATE_NEXT(); + goto value; + +scalar_string: + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + goto value_end; + +scalar: + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + break; + default: + return TAPE_ERROR; + } + // The scalar is not the last token, so the parsers read inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + switch (c) { + case 't': if (!atomparsing::is_valid_true_atom(json + index)) { return T_ATOM_ERROR; } break; + case 'f': if (!atomparsing::is_valid_false_atom(json + index)) { return F_ATOM_ERROR; } break; + case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (!atomparsing::is_valid_null_atom(json + index) && !atomparsing::is_valid_nan_atom(json + index)) { return N_ATOM_ERROR; } +#else + if (!atomparsing::is_valid_null_atom(json + index)) { return N_ATOM_ERROR; } +#endif + break; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': if (!atomparsing::is_valid_nan_atom(json + index)) { return TAPE_ERROR; } break; + case 'i': case 'I': if (!atomparsing::is_valid_inf_atom(json + index)) { return TAPE_ERROR; } break; +#endif + default: + if (numberparsing::parse_double(json + index).error()) { return NUMBER_ERROR; } + break; + } + +value_end: + SIMDJSON_VALIDATE_NEXT(); + if (c == ',') { + SIMDJSON_VALIDATE_NEXT(); + if (is_array[depth / 64] & (uint64_t(1) << (depth % 64))) { goto value; } + goto key; + } + if (c != (is_array[depth / 64] & (uint64_t(1) << (depth % 64)) ? ']' : '}')) { return TAPE_ERROR; } + +container_end: + if (--depth > 0) { goto value_end; } +#undef SIMDJSON_VALIDATE_NEXT + if (!streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_number(const number &value, const char *raw, V &visitor) { + switch (value.get_number_type()) { + case number_type::signed_integer: return visitor.on_int64(value.get_int64(), raw); + case number_type::unsigned_integer: return visitor.on_uint64(value.get_uint64(), raw); + case number_type::floating_point_number: return visitor.on_double(value.get_double(), raw); + default: return BIGINT_ERROR; + } +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_string(const uint8_t *quote, bool key, V &visitor) { + const uint8_t *const start = quote + 1; + // A string without escapes is passed as it is in the document. + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (const uint8_t *src = start;; src += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(src, scratch); + if (bs_quote.has_quote_first()) { + std::string_view text(reinterpret_cast(start), size_t(src - start) + size_t(bs_quote.quote_index())); + return key ? visitor.on_key(text) : visitor.on_string(text); + } + if (bs_quote.has_backslash()) { break; } + } + uint8_t *const end = parser->implementation->parse_string(start, _string_buf_loc, false); + if (!end) { return STRING_ERROR; } + std::string_view text(reinterpret_cast(_string_buf_loc), size_t(end - _string_buf_loc)); + _string_buf_loc = end; + return key ? visitor.on_key(text) : visitor.on_string(text); +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_scalar(const uint8_t *src, V &visitor) { + switch (*src) { + case 't': return atomparsing::is_valid_true_atom(src) ? visitor.on_bool(true) : T_ATOM_ERROR; + case 'f': return atomparsing::is_valid_false_atom(src) ? visitor.on_bool(false) : F_ATOM_ERROR; + case 'n': + if (atomparsing::is_valid_null_atom(src)) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } +#endif + return N_ATOM_ERROR; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + number value; + SIMDJSON_TRY(numberparsing::parse_number(src, value)); + return visit_number(value, reinterpret_cast(src), visitor); + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } + return TAPE_ERROR; + case 'i': case 'I': + if (atomparsing::is_valid_inf_atom(src)) { return visitor.on_double(std::numeric_limits::infinity(), reinterpret_cast(src)); } + return TAPE_ERROR; +#endif + default: + return TAPE_ERROR; + } +} + +template +simdjson_warn_unused error_code json_iterator::visit_container(V &visitor, token_position start, size_t parent_depth) { + const uint8_t *const json = token.buf; + token_position pos = start; + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // For each open container, the number of its elements so far, with the top bit set for an + // array. Deeper than the fixed stack allows, the stack moves to the heap. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + constexpr size_t FIXED_DEPTH = 64; + uint32_t fixed_stack[FIXED_DEPTH]; + std::unique_ptr heap_stack; + uint32_t *stack = fixed_stack; + size_t depth = parent_depth; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VISIT_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VISIT_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': + // A string is not the last token, so that its closing quote is inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, false, visitor)); + goto value_end; + default: + // The scalar is not the last token, so the parsers read inside the document. + if (simdjson_unlikely(pos == end)) { + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + return INCOMPLETE_ARRAY_OR_OBJECT; + default: + return TAPE_ERROR; + } + } + SIMDJSON_TRY(visit_scalar(json + index, visitor)); + goto value_end; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. + if (pos != end && json[*pos] == c + 2) { + pos++; + if (c == '[') { + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_TRY(visitor.on_array_end(0)); + } else { + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_TRY(visitor.on_object_end(0)); + } + if (depth == parent_depth) { goto document_end; } + goto value_end; + } + if (++depth >= max_depth) { return DEPTH_ERROR; } + // Copy the fixed stack once. A later container at this depth must keep the + // counts already stored on the heap. + if (depth >= FIXED_DEPTH && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint32_t[max_depth]); + if (!heap_stack) { return MEMALLOC; } + // Only the slots past the parent were written. + if (parent_depth + 1 < FIXED_DEPTH) { + std::memcpy(heap_stack.get() + parent_depth + 1, fixed_stack + parent_depth + 1, (FIXED_DEPTH - parent_depth - 1) * sizeof(fixed_stack[0])); + } + stack = heap_stack.get(); + } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_VISIT_NEXT(); + goto value; + } + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_VISIT_NEXT(); + +key: + if (c != '"') { return TAPE_ERROR; } + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, true, visitor)); + SIMDJSON_VISIT_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VISIT_NEXT(); + goto value; + +value_end: + SIMDJSON_VISIT_NEXT(); + if (c == ',') { + stack[depth]++; + SIMDJSON_VISIT_NEXT(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_object_end(stack[depth])); + } + if (--depth > parent_depth) { goto value_end; } + +document_end: +#undef SIMDJSON_VISIT_NEXT + if (parent_depth == 0 && !streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + simdjson_inline bool json_iterator::at_root() const noexcept { return position() == root_position(); } @@ -176687,10 +187279,20 @@ simdjson_warn_unused simdjson_inline bool json_iterator::copy_to_buffer(const ui // peek_root_length() stops at the next structural index. Stage 1 omits the // comma or RS (0x1E) that separates stream documents, so that byte and the // whitespace around it remain in the span. RS is not a valid number finisher. + // Outside of a stream, the comma and RS are not separators: some kernels + // keep RS in the scalar token, and dropping it would accept "1\x1e". while (max_len > 0) { const uint8_t last = json[max_len - 1]; + // iterate_allow_incomplete_json() reuses _streaming, so a root scalar + // there is not a document_stream. +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + const bool separator = _streaming && !_allow_incomplete_json && + (last == ',' || last == 0x1E); +#else + const bool separator = _streaming && (last == ',' || last == 0x1E); +#endif if (last != ' ' && last != '\t' && last != '\n' && last != '\r' && - last != ',' && last != 0x1E) { + !separator) { break; } max_len--; @@ -178120,22 +188722,22 @@ simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capa return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - std::unique_ptr new_string_buf(new (std::nothrow) uint8_t[string_capacity]); - if (!new_string_buf) { return MEMALLOC; } + simdjson::internal::allocated_array new_string_buf; + if (!new_string_buf.allocate(string_capacity, _allocator)) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr new_start_positions(new (std::nothrow) token_position[new_max_depth]); if (!new_start_positions) { return MEMALLOC; } #endif - if (implementation) { - error_code err = implementation->allocate(new_capacity, new_max_depth); - if (err) { return err; } - } else { - error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, new_max_depth, implementation); if (err) { implementation.reset(); return err; } } + implementation->allocator = _allocator; + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } string_buf = std::move(new_string_buf); #if SIMDJSON_DEVELOPMENT_CHECKS start_positions = std::move(new_start_positions); @@ -178164,9 +188766,42 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iterate(p // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return document::start({ reinterpret_cast(json.data()), this }); } +// Removes from the structural indexes each comma that follows a value and +// precedes a closing bracket, so that the iterator never sees it. The entries +// past the last index (stage 1 keeps up to three there) move with the others. +#if SIMDJSON_ALLOW_TRAILING_COMMAS +simdjson_inline void parser::drop_trailing_commas(const uint8_t *buf) noexcept { + uint32_t *indexes = implementation->structural_indexes.get(); + const uint32_t n = implementation->n_structural_indexes; + uint32_t kept = 0; + uint8_t previous = '['; + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = buf[indexes[i]]; + if (c == ',' && i + 1 < n && previous != '[' && previous != '{' && previous != ',' && previous != ':') { + const uint8_t next = buf[indexes[i + 1]]; + if (next == ']' || next == '}') { + previous = c; + continue; + } + } + indexes[kept++] = indexes[i]; + previous = c; + } + if (kept != n) { + indexes[kept] = indexes[n]; + indexes[kept + 1] = indexes[n + 1]; + indexes[kept + 2] = indexes[n + 2]; + implementation->n_structural_indexes = kept; + } +} +#endif // SIMDJSON_ALLOW_TRAILING_COMMAS + #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_warn_unused simdjson_inline simdjson_result parser::iterate_allow_incomplete_json(padded_string_view json) & noexcept { if (!json.has_sufficient_padding()) { return INSUFFICIENT_PADDING; } @@ -178270,9 +188905,210 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iter // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return json_iterator(reinterpret_cast(json.data()), this); } +namespace { +struct ignoring_visitor { + simdjson_inline error_code on_object_start() { return SUCCESS; } + simdjson_inline error_code on_object_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_array_start() { return SUCCESS; } + simdjson_inline error_code on_array_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_key(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_string(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_int64(int64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_uint64(uint64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_double(double, const char *) { return SUCCESS; } + simdjson_inline error_code on_bool(bool) { return SUCCESS; } + simdjson_inline error_code on_null() { return SUCCESS; } +}; +} // unnamed namespace + +template +simdjson_warn_unused simdjson_inline error_code parser::visit(padded_string_view json, V &visitor) & { +#if !SIMDJSON_ENABLE_NAN_INF && !SIMDJSON_ALLOW_TRAILING_COMMAS + if (json.length() <= MAX_ONE_PASS_VISIT && json.has_sufficient_padding()) { + if (capacity() < json.length() || !string_buf) { + SIMDJSON_TRY( allocate(json.length(), max_depth()) ); + } + bool visitor_failed = false; + const error_code error = visit_one_pass(reinterpret_cast(json.data()), json.length(), visitor, visitor_failed); + if (error != UNINITIALIZED) { + if (error != TAPE_ERROR || visitor_failed) { return error; } + // The visitor has already seen part of the document: the regular walk only finds the + // error code, and never calls the visitor a second time. + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + ignoring_visitor ignoring; + const error_code regular_error = doc.visit(ignoring); + return regular_error ? regular_error : TAPE_ERROR; + } + } +#endif + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + return doc.visit(visitor); +} + +// A single pass over the bytes, for small documents. The root must be an array or an object, and +// the last byte that is not whitespace must be ] or }: before it, runs of whitespace, digits or +// atoms stop without a bound check. Only a closing bracket or a string may reach the end. +template +simdjson_warn_unused simdjson_inline error_code parser::visit_one_pass(const uint8_t *const buf, const size_t len, V &visitor, bool &visitor_failed) { + const auto is_whitespace = [](uint8_t c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; + if (len == 0 || len > MAX_ONE_PASS_VISIT) { return UNINITIALIZED; } + const uint8_t *p = buf; + const uint8_t *last = buf + len - 1; + while (p < last && is_whitespace(*p)) { p++; } + while (last > p && is_whitespace(*last)) { last--; } + if ((*p != '{' && *p != '[') || (*last != '}' && *last != ']')) { return UNINITIALIZED; } + const uint8_t *const end = last + 1; + uint8_t *dst = string_buf.get(); + bool non_ascii = false; + // For each open container, the number of its elements so far, with the top bit set for an + // array. Each container opens at a distinct byte before the last one, so that the depth stays + // below MAX_ONE_PASS_VISIT. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + uint32_t stack[MAX_ONE_PASS_VISIT]; + size_t depth = 0; + uint8_t c = *p; + +#define SIMDJSON_ONE_PASS_CALL(EXPR) \ + do { \ + const error_code one_pass_error = (EXPR); \ + if (simdjson_unlikely(one_pass_error != SUCCESS)) { visitor_failed = true; return one_pass_error; } \ + } while (0) +#define SIMDJSON_ONE_PASS_WHITESPACE() while (is_whitespace(*p)) { p++; } +// The string at p, which is left past the closing quote. +#define SIMDJSON_ONE_PASS_STRING(METHOD) \ + do { \ + const uint8_t *const start = ++p; \ + bool escaped = false; \ + for (;; p++) { \ + if (simdjson_unlikely(p >= end)) { return TAPE_ERROR; } \ + if (*p == '"') { break; } \ + if (*p == '\\') { \ + escaped = true; \ + p++; \ + } else if (simdjson_unlikely(*p < 0x20)) { \ + return TAPE_ERROR; \ + } else if (*p >= 0x80) { \ + non_ascii = true; \ + } \ + } \ + std::string_view text(reinterpret_cast(start), size_t(p - start)); \ + p++; \ + if (escaped) { \ + uint8_t *const unescaped_end = implementation->parse_string(start, dst, false); \ + if (unescaped_end == nullptr) { return TAPE_ERROR; } \ + text = std::string_view(reinterpret_cast(dst), size_t(unescaped_end - dst)); \ + dst = unescaped_end; \ + } \ + SIMDJSON_ONE_PASS_CALL(visitor.METHOD(text)); \ + } while (0) + + goto container_start; + +value: + switch (*p) { + case '{': case '[': + c = *p; + goto container_start; + case '"': + SIMDJSON_ONE_PASS_STRING(on_string); + goto value_end; + case 't': + if (!atomparsing::is_valid_true_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(true)); + p += 4; + goto value_end; + case 'f': + if (!atomparsing::is_valid_false_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(false)); + p += 5; + goto value_end; + case 'n': + if (!atomparsing::is_valid_null_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_null()); + p += 4; + goto value_end; + default: { + number value; + if (numberparsing::parse_number(p, value) != SUCCESS) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(json_iterator::visit_number(value, reinterpret_cast(p), visitor)); + while (jsoncharutils::is_not_structural_or_whitespace(*p)) { p++; } + goto value_end; + } + } + +container_start: + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + // As in DOM, an empty container does not count toward the maximal depth. + if (*p == c + 2) { + p++; + if (c == '[') { + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(0)); + } else { + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(0)); + } + if (depth == 0) { goto document_end; } + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + if (++depth >= max_depth()) { return TAPE_ERROR; } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + goto value; + } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + +key: + if (*p != '"') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_STRING(on_key); + SIMDJSON_ONE_PASS_WHITESPACE(); + if (*p != ':') { return TAPE_ERROR; } + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + goto value; + +value_end: + SIMDJSON_ONE_PASS_WHITESPACE(); + c = *p++; + if (c == ',') { + stack[depth]++; + SIMDJSON_ONE_PASS_WHITESPACE(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(stack[depth])); + } + if (--depth > 0) { + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + +document_end: +#undef SIMDJSON_ONE_PASS_CALL +#undef SIMDJSON_ONE_PASS_WHITESPACE +#undef SIMDJSON_ONE_PASS_STRING + if (p != end) { return TAPE_ERROR; } + if (non_ascii && !simdjson::validate_utf8(reinterpret_cast(buf), len)) { return TAPE_ERROR; } + return SUCCESS; +} + inline simdjson_result parser::iterate_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept { if(batch_size < MINIMAL_BATCH_SIZE) { batch_size = MINIMAL_BATCH_SIZE; } if((len >= 3) && (std::memcmp(buf, "\xEF\xBB\xBF", 3) == 0)) { @@ -178390,6 +189226,13 @@ simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return _max_depth; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} + simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept { if(max_capacity > dom::MINIMAL_DOCUMENT_CAPACITY) { _max_capacity = max_capacity; @@ -178909,13 +189752,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_objec _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing } at end"); } - // If the last character is } *and* the first gibberish character is also '}' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is } *and* the first gibberish character is '}', ']' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == '}') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed object. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -179319,13 +190164,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_array _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing ] at end"); } - // If the last character is ] *and* the first gibberish character is also ']' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is ] *and* the first gibberish character is ']', '}' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == ']') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed array. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -179495,7 +190342,7 @@ simdjson_inline simdjson_result value_iterator::get_root_ // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -179519,7 +190366,7 @@ simdjson_inline simdjson_result value_iterator::get_root_number(bool che // number: -0.e-308. // NOTE: the current approach doesn't work for very big integer numbers containing more than 1074 digits. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -179601,7 +190448,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::g simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer tmpbuf[20+1] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+1)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 20 characters"); @@ -179618,7 +190465,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::ge simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64_in_string(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer tmpbuf[20+2] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+2)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 22 characters"); @@ -179639,7 +190486,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -179661,7 +190508,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -179683,7 +190530,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ // digits that matter is smaller for binary32, but the JSON document may still // spell out a long number that we must parse (and round) faithfully. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -179702,7 +190549,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ auto max_len = peek_root_length(); auto json = peek_root_scalar("float"); // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -180040,6 +190887,9 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '"': return json_type::string; case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } +#endif return json_type::null; case 't': case 'f': return json_type::boolean; @@ -180047,6 +190897,14 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return json_type::number; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; + case 'I': case 'i': + if (atomparsing::is_valid_inf_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; +#endif default: return json_type::unknown; } @@ -181182,6 +192040,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lsx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lsx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -181191,14 +192050,11 @@ namespace lsx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -181423,6 +192279,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 16 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[16]; + std::memset(block, fill, 16); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m128i _value) : base8_numeric(_value) {} // Splat constructor @@ -183080,6 +193944,23 @@ class value { */ simdjson_inline std::string_view raw_json_token() noexcept; + /** + * Calls the visitor for this value and everything in it, as document::visit() does for a + * whole document, for example after navigating to a field: + * + * auto error = doc["payload"].visit(visitor); + * + * The value must not have been read. The walk does not move the iterator: to go on, read the + * value or the next field or element as usual. A string with escapes is valid until you read + * the document further or visit again. The maximal depth counts from the root of the document. + * A value at the root also fails if anything follows it. + * + * @returns SUCCESS, OUT_OF_ORDER_ITERATION if the value has been read, the first error found + * in the value, or the first error the visitor returns. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); + /** * Get a string_view pointing at this value in the JSON document. * If this element is an array or an object, it consumes the array or the object @@ -183397,6 +194278,8 @@ struct simdjson_result : public lsx::implementation_simdjs /** @copydoc simdjson_inline std::string_view value::raw_json_token() const noexcept */ simdjson_inline simdjson_result raw_json_token() noexcept; simdjson_inline simdjson_result raw_json() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** @copydoc simdjson_inline simdjson_result current_location() noexcept */ simdjson_inline simdjson_result current_location() noexcept; @@ -183742,6 +194625,29 @@ class json_iterator { simdjson_inline error_code out_of_place_error() noexcept; /** Tells whether the string before pos, followed by a colon, is a key. */ static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; + /** + * Validates the array or object at the current position and everything in it, without + * recursion. Outside of streaming mode, it also checks that nothing follows it. It does + * not move the iterator. + */ + simdjson_warn_unused error_code validate_container() noexcept; + static simdjson_inline bool has_backslash(const uint8_t *src, size_t len) noexcept; + /** + * Calls the visitor for the array or object at the start position and everything in it, + * without recursion (see document::visit()). The container is at depth parent_depth + 1. At + * the root (parent_depth == 0) and outside of streaming mode, it also checks that nothing + * follows it. It does not move the iterator. Escaped strings are copied into the string + * buffer. + */ + template + simdjson_warn_unused error_code visit_container(V &visitor, token_position start, size_t parent_depth); + template + simdjson_warn_unused simdjson_inline error_code visit_string(const uint8_t *quote, bool key, V &visitor); + template + simdjson_warn_unused simdjson_inline error_code visit_scalar(const uint8_t *src, V &visitor); + /** Calls the visitor for a number that numberparsing::parse_number accepted. */ + template + static simdjson_warn_unused simdjson_inline error_code visit_number(const number &value, const char *raw, V &visitor); /** * Tell whether the iterator is still at the start @@ -183931,7 +194837,8 @@ class json_iterator { /** * Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with * N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero. - * Trailing whitespace, commas, and record separators (0x1E) do not count toward max_len. + * Trailing whitespace does not count toward max_len. A comma or record + * separator (0x1E) is ignored only for a document stream. * The buffer (tmpbuf) is padded with space characters. */ simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept; @@ -184627,6 +195534,33 @@ class parser { */ simdjson_warn_unused simdjson_result iterate_raw(padded_string_view json) & noexcept; + /** + * Parses the document and walks it once with the visitor: the same as iterate() followed by + * document::visit(), with the same values and, when the visitor returns SUCCESS, the same + * error code, but faster on small documents. + * + * counting_visitor visitor; + * auto error = parser.visit(R"({"stars":[1,2,3]})"_padded, visitor); + * + * A document of at most MAX_ONE_PASS_VISIT bytes whose root is an object or an array is read in + * a single pass, without the structural index that iterate() builds. Some checks, such as the + * UTF-8 validation, then come at the end of the walk: on an invalid document, the visitor may + * have seen part or all of it before visit() returns the error code of document::visit(), and + * an error returned by the visitor may come first. With SIMDJSON_ENABLE_NAN_INF or + * SIMDJSON_ALLOW_TRAILING_COMMAS, there is no one-pass walk. + * + * See document::visit() for the methods of the visitor and the lifetime of the strings. + * + * @param json The JSON to parse, with at least SIMDJSON_PADDING bytes after it. + * @param visitor The visitor. + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(padded_string_view json, V &visitor) &; + /** Documents of at most this many bytes may be visited in one pass, see visit(). */ + static constexpr size_t MAX_ONE_PASS_VISIT = 32; + /** * Parse a buffer containing many JSON documents. @@ -184785,6 +195719,20 @@ class parser { */ simdjson_pure simdjson_inline size_t max_depth() const noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the string buffer and the structural indexes) through a buffer_allocator. + * nullptr, the default, uses new[]. The allocator must outlive the parser. + * + * Buffers that the parser already holds keep the allocator that allocated + * them until the parser grows them, so set the allocator before the first + * document or the first call to allocate(). A failed allocation makes the + * parser return MEMALLOC and leaves its buffers as they were. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + /** * Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length * and `max_depth` depth. @@ -184894,17 +195842,27 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr& get_threadlocal_parser_if_exists(); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + simdjson_inline void drop_trailing_commas(const uint8_t *buf) noexcept; +#endif #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** + * The one-pass walk of visit(). Returns UNINITIALIZED when it does not handle the document, + * and TAPE_ERROR when the document is invalid. visitor_failed tells an error of the visitor. + */ + template + simdjson_warn_unused simdjson_inline error_code visit_one_pass(const uint8_t *buf, size_t len, V &visitor, bool &visitor_failed); /** @private [for benchmarking access] The implementation to use */ std::unique_ptr implementation{}; size_t _capacity{0}; size_t _max_capacity; size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; - std::unique_ptr string_buf{}; + simdjson::internal::allocated_array string_buf{}; + const buffer_allocator *_allocator{nullptr}; #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; @@ -186162,6 +197120,58 @@ class document { * left as is. */ inline void rewind() noexcept; + /** + * Validates the whole document: its structure, every string (escapes included), every + * number, true, false and null, and that nothing follows the root value. Strings are + * checked as get_string() checks them and numbers as get_double() does. The document is + * rewound before and after, so that it can be iterated after a successful validation. + * + * It is faster than iterating through every value, because it walks the tokens directly, + * without creating values, arrays or objects. + * + * @returns SUCCESS if the document is valid, or the error found first. + */ + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + /** + * Walks the whole document once and calls the visitor for each value, in document order. + * Use it to build your own representation of the document (a tree, columns, ...) faster + * than by iterating, as the walk creates no values, arrays or objects. + * + * The visitor provides these methods. Each returns an error_code: anything but SUCCESS stops + * the walk, and visit() returns it. + * + * error_code on_object_start(); + * error_code on_object_end(uint32_t member_count); + * error_code on_array_start(); + * error_code on_array_end(uint32_t element_count); + * error_code on_key(std::string_view key); // before each member value + * error_code on_string(std::string_view value); + * error_code on_int64(int64_t value, const char *raw); // integers that fit an int64_t + * error_code on_uint64(uint64_t value, const char *raw); // larger positive integers + * error_code on_double(double value, const char *raw); + * error_code on_bool(bool value); + * error_code on_null(); + * + * raw points at the number in the document, so that the visitor can tell -0 from 0, for + * example. As with the DOM parser, an integer that does not fit in 64 bits is a BIGINT_ERROR. + * + * A key or a string without escapes is a view into the document: it is valid as long as the + * document's bytes are. A key or a string with escapes is unescaped into the parser: it is + * valid until the document is iterated or visited again, or the parser parses another + * document. + * + * visit() succeeds exactly when the DOM parser does. An error may come after the visitor has + * seen part of the document. The document is rewound before and after the walk, so that it + * can be iterated afterwards. The visitor may throw: the exception goes through visit(), and + * the document must then be rewound before it is used again. + * + * To parse and visit a document in one call, faster on small documents, see parser::visit(). + * + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** * Returns debugging information. */ @@ -186332,6 +197342,9 @@ class document { simdjson_inline value_iterator resume_value_iterator() noexcept; simdjson_inline value_iterator get_root_value_iterator() noexcept; + /** The walk of visit(), between its two rewinds. */ + template + simdjson_warn_unused simdjson_inline error_code visit_root(V &visitor); simdjson_inline simdjson_result start_or_resume_object() noexcept; static simdjson_inline document start(ondemand::json_iterator &&iter) noexcept; @@ -186551,6 +197564,9 @@ struct simdjson_result : public lsx::implementation_sim simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); simdjson_inline simdjson_result get_array() & noexcept; simdjson_inline simdjson_result get_object() & noexcept; @@ -189838,6 +200854,7 @@ inline std::ostream& operator<<(std::ostream& out, simdjson::simdjson_result #include +#include #if SIMDJSON_STATIC_REFLECTION #include #include @@ -190047,9 +201064,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { SIMDJSON_TRY(v.get(scratch.elements.emplace_back())); release.parsed++; } - out.reserve(release.parsed); - release.complete = true; - for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + if constexpr (std::is_trivially_copyable_v) { + out.assign(scratch.elements.begin(), scratch.elements.end()); + release.complete = true; + } else if (sizeof(value_type) <= 32 && scratch.elements.capacity() / 2 < release.parsed) { + // Hand the buffer over only when it is at least half full, so that out + // does not keep the capacity of an earlier, larger array. Swapping + // large structs is slower than moving them (recipe_book benchmark). + size_t const capacity = scratch.elements.capacity(); + out.swap(scratch.elements); + release.complete = true; + if (capacity * sizeof(value_type) <= (1 << 20)) { scratch.elements.reserve(capacity); } + } else { + out.reserve(release.parsed); + release.complete = true; + for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + } return SUCCESS; } } @@ -190279,7 +201309,11 @@ consteval void append_eligible_fields(std::meta::info type, std::vector(std::meta::substitute(^^flattenable_type, {flattened}))) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member whose type is a structure deserialized member by member", mem); +#else + simdjson::detail::flatten_requires_a_member_deserialized_member_by_member(); +#endif } append_eligible_fields(flattened, prefix, fields); } else { @@ -191635,6 +202669,27 @@ simdjson_warn_unused simdjson_inline simdjson_result value::get_number() return iter.get_number(); } +template +simdjson_warn_unused simdjson_inline error_code value::visit(V &visitor) { + if (!iter.is_at_start()) { return OUT_OF_ORDER_ITERATION; } + json_iterator &json_iter = iter.json_iter(); + const uint8_t *const json = iter.peek_start(); + // The escaped strings of the value go where reading it would put them, so that the string + // buffer has room for them however many times the value is visited. + uint8_t *const string_buf_loc = json_iter._string_buf_loc; + error_code error; + switch (*json) { + case '{': case '[': + error = json_iter.visit_container(visitor, iter.start_position(), size_t(iter.depth() - 1)); + break; + // A scalar value is nested in a container: its parser reads inside the document. + case '"': error = json_iter.visit_string(json, false, visitor); break; + default: error = json_iter.visit_scalar(json, visitor); break; + } + json_iter._string_buf_loc = string_buf_loc; + return error; +} + simdjson_inline std::string_view value::raw_json_token() noexcept { return std::string_view(reinterpret_cast(iter.peek_start()), iter.peek_start_length()); } @@ -192046,6 +203101,12 @@ simdjson_inline simdjson_result::operator bool() noexcept( } #endif +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + simdjson_inline simdjson_result simdjson_result::raw_json_token() noexcept { if (error()) { return error(); } return first.raw_json_token(); @@ -192141,6 +203202,124 @@ inline void document::rewind() noexcept { static_cast(iter.rewind()); } +simdjson_warn_unused simdjson_inline error_code document::validate() noexcept { + SIMDJSON_TRY(iter.rewind()); + const bool check_trailing = !iter.streaming(); + const uint8_t first = *iter.peek(); + error_code error; + switch (first) { + case '{': case '[': + error = iter.validate_container(); + break; + case '"': + error = get_root_value_iterator().get_root_string(check_trailing, false).error(); + break; + case 't': case 'f': + error = get_root_value_iterator().get_root_bool(check_trailing).error(); + break; + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && !null_value) { error = N_ATOM_ERROR; } +#if SIMDJSON_ENABLE_NAN_INF + if (error && !get_root_value_iterator().get_root_double(check_trailing).error()) { error = SUCCESS; } +#endif + break; + } + default: + error = get_root_value_iterator().get_root_double(check_trailing).error(); + break; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit(V &visitor) { + SIMDJSON_TRY(iter.rewind()); + const error_code error = visit_root(visitor); + // The strings of the walk stay in the buffer, but an iteration may start from its beginning. + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit_root(V &visitor) { + const bool check_trailing = !iter.streaming(); + const uint8_t *const first = iter.peek(); + const char *const raw = reinterpret_cast(first); + error_code error; + switch (*first) { + case '{': case '[': + return iter.visit_container(visitor, iter.position(), 0); + case '"': { + raw_json_string text; + error = get_root_value_iterator().get_root_raw_json_string(check_trailing).get(text); + if (!error) { return iter.visit_string(first, false, visitor); } + break; + } + case 't': case 'f': { + bool value; + error = get_root_value_iterator().get_root_bool(check_trailing).get(value); + if (!error) { return visitor.on_bool(value); } + break; + } + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && null_value) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + double value; + if (!get_root_value_iterator().get_root_double(check_trailing).get(value)) { return visitor.on_double(value, raw); } +#endif + if (!error) { error = N_ATOM_ERROR; } + break; + } + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + number value; + error = get_root_value_iterator().get_root_number(check_trailing).get(value); + if (!error) { return json_iterator::visit_number(value, raw, visitor); } + break; + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': { + double value; + error = get_root_value_iterator().get_root_double(check_trailing).get(value); + if (!error) { return visitor.on_double(value, raw); } + return error == TRAILING_CONTENT ? error : TAPE_ERROR; + } +#endif + default: + return TAPE_ERROR; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (*first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + return error; +} + inline std::string document::to_debug_string() noexcept { return iter.to_string(); } @@ -192695,6 +203874,16 @@ simdjson_inline error_code simdjson_result::rewind() no first.rewind(); return SUCCESS; } +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + +simdjson_warn_unused simdjson_inline error_code simdjson_result::validate() noexcept { + if (error()) { return error(); } + return first.validate(); +} simdjson_inline simdjson_result simdjson_result::begin() & noexcept { if (error()) { return error(); } return first.begin(); @@ -193765,6 +204954,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } worker->start_thread(); @@ -194018,6 +205208,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch @@ -194033,6 +205226,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -194374,6 +205570,8 @@ simdjson_inline simdjson_result simdjson_result= 8; src += 8, len -= 8) { + std::memcpy(&word, src, sizeof(word)); + word ^= BACKSLASHES; + if ((word - ONES) & ~word & HIGHS) { return true; } + } + uint64_t keep; + std::memcpy(&keep, KEEP + 8 - len, sizeof(keep)); + std::memcpy(&word, src, sizeof(word)); + word = (word ^ BACKSLASHES) | ~keep; + return ((word - ONES) & ~word & HIGHS) != 0; +} + +simdjson_warn_unused simdjson_never_inline error_code json_iterator::validate_container() noexcept { + const uint8_t *const json = token.buf; + token_position pos = token.position(); + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // One bit per depth tells whether the container at that depth is an array. Deeper than + // the fixed stack allows, the bits move to the heap. + uint64_t fixed_stack[16]{}; + std::unique_ptr heap_stack; + uint64_t *is_array = fixed_stack; + size_t depth = 0; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VALIDATE_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VALIDATE_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': goto scalar_string; + default: goto scalar; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. Its bit may then + // be at max_depth, which the stack has room for. + if (++depth >= max_depth && (pos == end || json[*pos] != c + 2)) { return DEPTH_ERROR; } + // The bits move once: the next time this depth is reached, the heap holds the current + // bits and the fixed stack holds stale ones. + if (depth == sizeof(fixed_stack) * 8 && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint64_t[max_depth / 64 + 1]()); + if (!heap_stack) { return MEMALLOC; } + std::memcpy(heap_stack.get(), fixed_stack, sizeof(fixed_stack)); + is_array = heap_stack.get(); + } + if (c == '[') { + is_array[depth / 64] |= uint64_t(1) << (depth % 64); + SIMDJSON_VALIDATE_NEXT(); + if (c == ']') { goto container_end; } + goto value; + } + is_array[depth / 64] &= ~(uint64_t(1) << (depth % 64)); + SIMDJSON_VALIDATE_NEXT(); + if (c == '}') { goto container_end; } + goto key; + +key: + if (c != '"') { return TAPE_ERROR; } + // A string is valid once stage 1 has accepted the document, unless it holds an escape. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + SIMDJSON_VALIDATE_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VALIDATE_NEXT(); + goto value; + +scalar_string: + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + goto value_end; + +scalar: + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + break; + default: + return TAPE_ERROR; + } + // The scalar is not the last token, so the parsers read inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + switch (c) { + case 't': if (!atomparsing::is_valid_true_atom(json + index)) { return T_ATOM_ERROR; } break; + case 'f': if (!atomparsing::is_valid_false_atom(json + index)) { return F_ATOM_ERROR; } break; + case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (!atomparsing::is_valid_null_atom(json + index) && !atomparsing::is_valid_nan_atom(json + index)) { return N_ATOM_ERROR; } +#else + if (!atomparsing::is_valid_null_atom(json + index)) { return N_ATOM_ERROR; } +#endif + break; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': if (!atomparsing::is_valid_nan_atom(json + index)) { return TAPE_ERROR; } break; + case 'i': case 'I': if (!atomparsing::is_valid_inf_atom(json + index)) { return TAPE_ERROR; } break; +#endif + default: + if (numberparsing::parse_double(json + index).error()) { return NUMBER_ERROR; } + break; + } + +value_end: + SIMDJSON_VALIDATE_NEXT(); + if (c == ',') { + SIMDJSON_VALIDATE_NEXT(); + if (is_array[depth / 64] & (uint64_t(1) << (depth % 64))) { goto value; } + goto key; + } + if (c != (is_array[depth / 64] & (uint64_t(1) << (depth % 64)) ? ']' : '}')) { return TAPE_ERROR; } + +container_end: + if (--depth > 0) { goto value_end; } +#undef SIMDJSON_VALIDATE_NEXT + if (!streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_number(const number &value, const char *raw, V &visitor) { + switch (value.get_number_type()) { + case number_type::signed_integer: return visitor.on_int64(value.get_int64(), raw); + case number_type::unsigned_integer: return visitor.on_uint64(value.get_uint64(), raw); + case number_type::floating_point_number: return visitor.on_double(value.get_double(), raw); + default: return BIGINT_ERROR; + } +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_string(const uint8_t *quote, bool key, V &visitor) { + const uint8_t *const start = quote + 1; + // A string without escapes is passed as it is in the document. + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (const uint8_t *src = start;; src += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(src, scratch); + if (bs_quote.has_quote_first()) { + std::string_view text(reinterpret_cast(start), size_t(src - start) + size_t(bs_quote.quote_index())); + return key ? visitor.on_key(text) : visitor.on_string(text); + } + if (bs_quote.has_backslash()) { break; } + } + uint8_t *const end = parser->implementation->parse_string(start, _string_buf_loc, false); + if (!end) { return STRING_ERROR; } + std::string_view text(reinterpret_cast(_string_buf_loc), size_t(end - _string_buf_loc)); + _string_buf_loc = end; + return key ? visitor.on_key(text) : visitor.on_string(text); +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_scalar(const uint8_t *src, V &visitor) { + switch (*src) { + case 't': return atomparsing::is_valid_true_atom(src) ? visitor.on_bool(true) : T_ATOM_ERROR; + case 'f': return atomparsing::is_valid_false_atom(src) ? visitor.on_bool(false) : F_ATOM_ERROR; + case 'n': + if (atomparsing::is_valid_null_atom(src)) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } +#endif + return N_ATOM_ERROR; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + number value; + SIMDJSON_TRY(numberparsing::parse_number(src, value)); + return visit_number(value, reinterpret_cast(src), visitor); + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } + return TAPE_ERROR; + case 'i': case 'I': + if (atomparsing::is_valid_inf_atom(src)) { return visitor.on_double(std::numeric_limits::infinity(), reinterpret_cast(src)); } + return TAPE_ERROR; +#endif + default: + return TAPE_ERROR; + } +} + +template +simdjson_warn_unused error_code json_iterator::visit_container(V &visitor, token_position start, size_t parent_depth) { + const uint8_t *const json = token.buf; + token_position pos = start; + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // For each open container, the number of its elements so far, with the top bit set for an + // array. Deeper than the fixed stack allows, the stack moves to the heap. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + constexpr size_t FIXED_DEPTH = 64; + uint32_t fixed_stack[FIXED_DEPTH]; + std::unique_ptr heap_stack; + uint32_t *stack = fixed_stack; + size_t depth = parent_depth; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VISIT_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VISIT_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': + // A string is not the last token, so that its closing quote is inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, false, visitor)); + goto value_end; + default: + // The scalar is not the last token, so the parsers read inside the document. + if (simdjson_unlikely(pos == end)) { + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + return INCOMPLETE_ARRAY_OR_OBJECT; + default: + return TAPE_ERROR; + } + } + SIMDJSON_TRY(visit_scalar(json + index, visitor)); + goto value_end; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. + if (pos != end && json[*pos] == c + 2) { + pos++; + if (c == '[') { + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_TRY(visitor.on_array_end(0)); + } else { + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_TRY(visitor.on_object_end(0)); + } + if (depth == parent_depth) { goto document_end; } + goto value_end; + } + if (++depth >= max_depth) { return DEPTH_ERROR; } + // Copy the fixed stack once. A later container at this depth must keep the + // counts already stored on the heap. + if (depth >= FIXED_DEPTH && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint32_t[max_depth]); + if (!heap_stack) { return MEMALLOC; } + // Only the slots past the parent were written. + if (parent_depth + 1 < FIXED_DEPTH) { + std::memcpy(heap_stack.get() + parent_depth + 1, fixed_stack + parent_depth + 1, (FIXED_DEPTH - parent_depth - 1) * sizeof(fixed_stack[0])); + } + stack = heap_stack.get(); + } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_VISIT_NEXT(); + goto value; + } + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_VISIT_NEXT(); + +key: + if (c != '"') { return TAPE_ERROR; } + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, true, visitor)); + SIMDJSON_VISIT_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VISIT_NEXT(); + goto value; + +value_end: + SIMDJSON_VISIT_NEXT(); + if (c == ',') { + stack[depth]++; + SIMDJSON_VISIT_NEXT(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_object_end(stack[depth])); + } + if (--depth > parent_depth) { goto value_end; } + +document_end: +#undef SIMDJSON_VISIT_NEXT + if (parent_depth == 0 && !streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + simdjson_inline bool json_iterator::at_root() const noexcept { return position() == root_position(); } @@ -195014,10 +206541,20 @@ simdjson_warn_unused simdjson_inline bool json_iterator::copy_to_buffer(const ui // peek_root_length() stops at the next structural index. Stage 1 omits the // comma or RS (0x1E) that separates stream documents, so that byte and the // whitespace around it remain in the span. RS is not a valid number finisher. + // Outside of a stream, the comma and RS are not separators: some kernels + // keep RS in the scalar token, and dropping it would accept "1\x1e". while (max_len > 0) { const uint8_t last = json[max_len - 1]; + // iterate_allow_incomplete_json() reuses _streaming, so a root scalar + // there is not a document_stream. +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + const bool separator = _streaming && !_allow_incomplete_json && + (last == ',' || last == 0x1E); +#else + const bool separator = _streaming && (last == ',' || last == 0x1E); +#endif if (last != ' ' && last != '\t' && last != '\n' && last != '\r' && - last != ',' && last != 0x1E) { + !separator) { break; } max_len--; @@ -196447,22 +207984,22 @@ simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capa return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - std::unique_ptr new_string_buf(new (std::nothrow) uint8_t[string_capacity]); - if (!new_string_buf) { return MEMALLOC; } + simdjson::internal::allocated_array new_string_buf; + if (!new_string_buf.allocate(string_capacity, _allocator)) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr new_start_positions(new (std::nothrow) token_position[new_max_depth]); if (!new_start_positions) { return MEMALLOC; } #endif - if (implementation) { - error_code err = implementation->allocate(new_capacity, new_max_depth); - if (err) { return err; } - } else { - error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, new_max_depth, implementation); if (err) { implementation.reset(); return err; } } + implementation->allocator = _allocator; + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } string_buf = std::move(new_string_buf); #if SIMDJSON_DEVELOPMENT_CHECKS start_positions = std::move(new_start_positions); @@ -196491,9 +208028,42 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iterate(p // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return document::start({ reinterpret_cast(json.data()), this }); } +// Removes from the structural indexes each comma that follows a value and +// precedes a closing bracket, so that the iterator never sees it. The entries +// past the last index (stage 1 keeps up to three there) move with the others. +#if SIMDJSON_ALLOW_TRAILING_COMMAS +simdjson_inline void parser::drop_trailing_commas(const uint8_t *buf) noexcept { + uint32_t *indexes = implementation->structural_indexes.get(); + const uint32_t n = implementation->n_structural_indexes; + uint32_t kept = 0; + uint8_t previous = '['; + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = buf[indexes[i]]; + if (c == ',' && i + 1 < n && previous != '[' && previous != '{' && previous != ',' && previous != ':') { + const uint8_t next = buf[indexes[i + 1]]; + if (next == ']' || next == '}') { + previous = c; + continue; + } + } + indexes[kept++] = indexes[i]; + previous = c; + } + if (kept != n) { + indexes[kept] = indexes[n]; + indexes[kept + 1] = indexes[n + 1]; + indexes[kept + 2] = indexes[n + 2]; + implementation->n_structural_indexes = kept; + } +} +#endif // SIMDJSON_ALLOW_TRAILING_COMMAS + #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_warn_unused simdjson_inline simdjson_result parser::iterate_allow_incomplete_json(padded_string_view json) & noexcept { if (!json.has_sufficient_padding()) { return INSUFFICIENT_PADDING; } @@ -196597,9 +208167,210 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iter // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return json_iterator(reinterpret_cast(json.data()), this); } +namespace { +struct ignoring_visitor { + simdjson_inline error_code on_object_start() { return SUCCESS; } + simdjson_inline error_code on_object_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_array_start() { return SUCCESS; } + simdjson_inline error_code on_array_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_key(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_string(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_int64(int64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_uint64(uint64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_double(double, const char *) { return SUCCESS; } + simdjson_inline error_code on_bool(bool) { return SUCCESS; } + simdjson_inline error_code on_null() { return SUCCESS; } +}; +} // unnamed namespace + +template +simdjson_warn_unused simdjson_inline error_code parser::visit(padded_string_view json, V &visitor) & { +#if !SIMDJSON_ENABLE_NAN_INF && !SIMDJSON_ALLOW_TRAILING_COMMAS + if (json.length() <= MAX_ONE_PASS_VISIT && json.has_sufficient_padding()) { + if (capacity() < json.length() || !string_buf) { + SIMDJSON_TRY( allocate(json.length(), max_depth()) ); + } + bool visitor_failed = false; + const error_code error = visit_one_pass(reinterpret_cast(json.data()), json.length(), visitor, visitor_failed); + if (error != UNINITIALIZED) { + if (error != TAPE_ERROR || visitor_failed) { return error; } + // The visitor has already seen part of the document: the regular walk only finds the + // error code, and never calls the visitor a second time. + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + ignoring_visitor ignoring; + const error_code regular_error = doc.visit(ignoring); + return regular_error ? regular_error : TAPE_ERROR; + } + } +#endif + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + return doc.visit(visitor); +} + +// A single pass over the bytes, for small documents. The root must be an array or an object, and +// the last byte that is not whitespace must be ] or }: before it, runs of whitespace, digits or +// atoms stop without a bound check. Only a closing bracket or a string may reach the end. +template +simdjson_warn_unused simdjson_inline error_code parser::visit_one_pass(const uint8_t *const buf, const size_t len, V &visitor, bool &visitor_failed) { + const auto is_whitespace = [](uint8_t c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; + if (len == 0 || len > MAX_ONE_PASS_VISIT) { return UNINITIALIZED; } + const uint8_t *p = buf; + const uint8_t *last = buf + len - 1; + while (p < last && is_whitespace(*p)) { p++; } + while (last > p && is_whitespace(*last)) { last--; } + if ((*p != '{' && *p != '[') || (*last != '}' && *last != ']')) { return UNINITIALIZED; } + const uint8_t *const end = last + 1; + uint8_t *dst = string_buf.get(); + bool non_ascii = false; + // For each open container, the number of its elements so far, with the top bit set for an + // array. Each container opens at a distinct byte before the last one, so that the depth stays + // below MAX_ONE_PASS_VISIT. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + uint32_t stack[MAX_ONE_PASS_VISIT]; + size_t depth = 0; + uint8_t c = *p; + +#define SIMDJSON_ONE_PASS_CALL(EXPR) \ + do { \ + const error_code one_pass_error = (EXPR); \ + if (simdjson_unlikely(one_pass_error != SUCCESS)) { visitor_failed = true; return one_pass_error; } \ + } while (0) +#define SIMDJSON_ONE_PASS_WHITESPACE() while (is_whitespace(*p)) { p++; } +// The string at p, which is left past the closing quote. +#define SIMDJSON_ONE_PASS_STRING(METHOD) \ + do { \ + const uint8_t *const start = ++p; \ + bool escaped = false; \ + for (;; p++) { \ + if (simdjson_unlikely(p >= end)) { return TAPE_ERROR; } \ + if (*p == '"') { break; } \ + if (*p == '\\') { \ + escaped = true; \ + p++; \ + } else if (simdjson_unlikely(*p < 0x20)) { \ + return TAPE_ERROR; \ + } else if (*p >= 0x80) { \ + non_ascii = true; \ + } \ + } \ + std::string_view text(reinterpret_cast(start), size_t(p - start)); \ + p++; \ + if (escaped) { \ + uint8_t *const unescaped_end = implementation->parse_string(start, dst, false); \ + if (unescaped_end == nullptr) { return TAPE_ERROR; } \ + text = std::string_view(reinterpret_cast(dst), size_t(unescaped_end - dst)); \ + dst = unescaped_end; \ + } \ + SIMDJSON_ONE_PASS_CALL(visitor.METHOD(text)); \ + } while (0) + + goto container_start; + +value: + switch (*p) { + case '{': case '[': + c = *p; + goto container_start; + case '"': + SIMDJSON_ONE_PASS_STRING(on_string); + goto value_end; + case 't': + if (!atomparsing::is_valid_true_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(true)); + p += 4; + goto value_end; + case 'f': + if (!atomparsing::is_valid_false_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(false)); + p += 5; + goto value_end; + case 'n': + if (!atomparsing::is_valid_null_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_null()); + p += 4; + goto value_end; + default: { + number value; + if (numberparsing::parse_number(p, value) != SUCCESS) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(json_iterator::visit_number(value, reinterpret_cast(p), visitor)); + while (jsoncharutils::is_not_structural_or_whitespace(*p)) { p++; } + goto value_end; + } + } + +container_start: + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + // As in DOM, an empty container does not count toward the maximal depth. + if (*p == c + 2) { + p++; + if (c == '[') { + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(0)); + } else { + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(0)); + } + if (depth == 0) { goto document_end; } + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + if (++depth >= max_depth()) { return TAPE_ERROR; } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + goto value; + } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + +key: + if (*p != '"') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_STRING(on_key); + SIMDJSON_ONE_PASS_WHITESPACE(); + if (*p != ':') { return TAPE_ERROR; } + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + goto value; + +value_end: + SIMDJSON_ONE_PASS_WHITESPACE(); + c = *p++; + if (c == ',') { + stack[depth]++; + SIMDJSON_ONE_PASS_WHITESPACE(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(stack[depth])); + } + if (--depth > 0) { + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + +document_end: +#undef SIMDJSON_ONE_PASS_CALL +#undef SIMDJSON_ONE_PASS_WHITESPACE +#undef SIMDJSON_ONE_PASS_STRING + if (p != end) { return TAPE_ERROR; } + if (non_ascii && !simdjson::validate_utf8(reinterpret_cast(buf), len)) { return TAPE_ERROR; } + return SUCCESS; +} + inline simdjson_result parser::iterate_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept { if(batch_size < MINIMAL_BATCH_SIZE) { batch_size = MINIMAL_BATCH_SIZE; } if((len >= 3) && (std::memcmp(buf, "\xEF\xBB\xBF", 3) == 0)) { @@ -196717,6 +208488,13 @@ simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return _max_depth; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} + simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept { if(max_capacity > dom::MINIMAL_DOCUMENT_CAPACITY) { _max_capacity = max_capacity; @@ -197236,13 +209014,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_objec _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing } at end"); } - // If the last character is } *and* the first gibberish character is also '}' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is } *and* the first gibberish character is '}', ']' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == '}') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed object. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -197646,13 +209426,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_array _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing ] at end"); } - // If the last character is ] *and* the first gibberish character is also ']' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is ] *and* the first gibberish character is ']', '}' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == ']') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed array. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -197822,7 +209604,7 @@ simdjson_inline simdjson_result value_iterator::get_root_numbe // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -197846,7 +209628,7 @@ simdjson_inline simdjson_result value_iterator::get_root_number(bool che // number: -0.e-308. // NOTE: the current approach doesn't work for very big integer numbers containing more than 1074 digits. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -197928,7 +209710,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::g simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer tmpbuf[20+1] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+1)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 20 characters"); @@ -197945,7 +209727,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::ge simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64_in_string(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer tmpbuf[20+2] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+2)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 22 characters"); @@ -197966,7 +209748,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -197988,7 +209770,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -198010,7 +209792,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ // digits that matter is smaller for binary32, but the JSON document may still // spell out a long number that we must parse (and round) faithfully. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -198029,7 +209811,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ auto max_len = peek_root_length(); auto json = peek_root_scalar("float"); // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -198367,6 +210149,9 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '"': return json_type::string; case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } +#endif return json_type::null; case 't': case 'f': return json_type::boolean; @@ -198374,6 +210159,14 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return json_type::number; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; + case 'I': case 'i': + if (atomparsing::is_valid_inf_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; +#endif default: return json_type::unknown; } @@ -199525,6 +211318,7 @@ simdjson_inline uint64_t prefix_xor(uint64_t bitmask) { /* amalgamation skipped (editor-only): #include "simdjson/lasx/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/lasx/intrinsics.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -199534,14 +211328,11 @@ namespace lasx { namespace numberparsing { // we don't have appropriate instructions, so let us use a scalar function -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const uint8_t *chars) { uint64_t val; std::memcpy(&val, chars, sizeof(uint64_t)); - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } simdjson_inline internal::value128 full_multiplication(uint64_t value1, uint64_t value2) { @@ -199793,6 +211584,14 @@ namespace simd { // Unsigned bytes template<> struct simd8: base8_numeric { + // The n < 32 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[32]; + std::memset(block, fill, 32); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8() : base8_numeric() {} simdjson_inline simd8(const __m256i _value) : base8_numeric(_value) {} // Splat constructor @@ -201438,6 +213237,23 @@ class value { */ simdjson_inline std::string_view raw_json_token() noexcept; + /** + * Calls the visitor for this value and everything in it, as document::visit() does for a + * whole document, for example after navigating to a field: + * + * auto error = doc["payload"].visit(visitor); + * + * The value must not have been read. The walk does not move the iterator: to go on, read the + * value or the next field or element as usual. A string with escapes is valid until you read + * the document further or visit again. The maximal depth counts from the root of the document. + * A value at the root also fails if anything follows it. + * + * @returns SUCCESS, OUT_OF_ORDER_ITERATION if the value has been read, the first error found + * in the value, or the first error the visitor returns. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); + /** * Get a string_view pointing at this value in the JSON document. * If this element is an array or an object, it consumes the array or the object @@ -201755,6 +213571,8 @@ struct simdjson_result : public lasx::implementation_simd /** @copydoc simdjson_inline std::string_view value::raw_json_token() const noexcept */ simdjson_inline simdjson_result raw_json_token() noexcept; simdjson_inline simdjson_result raw_json() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** @copydoc simdjson_inline simdjson_result current_location() noexcept */ simdjson_inline simdjson_result current_location() noexcept; @@ -202100,6 +213918,29 @@ class json_iterator { simdjson_inline error_code out_of_place_error() noexcept; /** Tells whether the string before pos, followed by a colon, is a key. */ static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; + /** + * Validates the array or object at the current position and everything in it, without + * recursion. Outside of streaming mode, it also checks that nothing follows it. It does + * not move the iterator. + */ + simdjson_warn_unused error_code validate_container() noexcept; + static simdjson_inline bool has_backslash(const uint8_t *src, size_t len) noexcept; + /** + * Calls the visitor for the array or object at the start position and everything in it, + * without recursion (see document::visit()). The container is at depth parent_depth + 1. At + * the root (parent_depth == 0) and outside of streaming mode, it also checks that nothing + * follows it. It does not move the iterator. Escaped strings are copied into the string + * buffer. + */ + template + simdjson_warn_unused error_code visit_container(V &visitor, token_position start, size_t parent_depth); + template + simdjson_warn_unused simdjson_inline error_code visit_string(const uint8_t *quote, bool key, V &visitor); + template + simdjson_warn_unused simdjson_inline error_code visit_scalar(const uint8_t *src, V &visitor); + /** Calls the visitor for a number that numberparsing::parse_number accepted. */ + template + static simdjson_warn_unused simdjson_inline error_code visit_number(const number &value, const char *raw, V &visitor); /** * Tell whether the iterator is still at the start @@ -202289,7 +214130,8 @@ class json_iterator { /** * Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with * N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero. - * Trailing whitespace, commas, and record separators (0x1E) do not count toward max_len. + * Trailing whitespace does not count toward max_len. A comma or record + * separator (0x1E) is ignored only for a document stream. * The buffer (tmpbuf) is padded with space characters. */ simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept; @@ -202985,6 +214827,33 @@ class parser { */ simdjson_warn_unused simdjson_result iterate_raw(padded_string_view json) & noexcept; + /** + * Parses the document and walks it once with the visitor: the same as iterate() followed by + * document::visit(), with the same values and, when the visitor returns SUCCESS, the same + * error code, but faster on small documents. + * + * counting_visitor visitor; + * auto error = parser.visit(R"({"stars":[1,2,3]})"_padded, visitor); + * + * A document of at most MAX_ONE_PASS_VISIT bytes whose root is an object or an array is read in + * a single pass, without the structural index that iterate() builds. Some checks, such as the + * UTF-8 validation, then come at the end of the walk: on an invalid document, the visitor may + * have seen part or all of it before visit() returns the error code of document::visit(), and + * an error returned by the visitor may come first. With SIMDJSON_ENABLE_NAN_INF or + * SIMDJSON_ALLOW_TRAILING_COMMAS, there is no one-pass walk. + * + * See document::visit() for the methods of the visitor and the lifetime of the strings. + * + * @param json The JSON to parse, with at least SIMDJSON_PADDING bytes after it. + * @param visitor The visitor. + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(padded_string_view json, V &visitor) &; + /** Documents of at most this many bytes may be visited in one pass, see visit(). */ + static constexpr size_t MAX_ONE_PASS_VISIT = 32; + /** * Parse a buffer containing many JSON documents. @@ -203143,6 +215012,20 @@ class parser { */ simdjson_pure simdjson_inline size_t max_depth() const noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the string buffer and the structural indexes) through a buffer_allocator. + * nullptr, the default, uses new[]. The allocator must outlive the parser. + * + * Buffers that the parser already holds keep the allocator that allocated + * them until the parser grows them, so set the allocator before the first + * document or the first call to allocate(). A failed allocation makes the + * parser return MEMALLOC and leaves its buffers as they were. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + /** * Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length * and `max_depth` depth. @@ -203252,17 +215135,27 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr& get_threadlocal_parser_if_exists(); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + simdjson_inline void drop_trailing_commas(const uint8_t *buf) noexcept; +#endif #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** + * The one-pass walk of visit(). Returns UNINITIALIZED when it does not handle the document, + * and TAPE_ERROR when the document is invalid. visitor_failed tells an error of the visitor. + */ + template + simdjson_warn_unused simdjson_inline error_code visit_one_pass(const uint8_t *buf, size_t len, V &visitor, bool &visitor_failed); /** @private [for benchmarking access] The implementation to use */ std::unique_ptr implementation{}; size_t _capacity{0}; size_t _max_capacity; size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; - std::unique_ptr string_buf{}; + simdjson::internal::allocated_array string_buf{}; + const buffer_allocator *_allocator{nullptr}; #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; @@ -204520,6 +216413,58 @@ class document { * left as is. */ inline void rewind() noexcept; + /** + * Validates the whole document: its structure, every string (escapes included), every + * number, true, false and null, and that nothing follows the root value. Strings are + * checked as get_string() checks them and numbers as get_double() does. The document is + * rewound before and after, so that it can be iterated after a successful validation. + * + * It is faster than iterating through every value, because it walks the tokens directly, + * without creating values, arrays or objects. + * + * @returns SUCCESS if the document is valid, or the error found first. + */ + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + /** + * Walks the whole document once and calls the visitor for each value, in document order. + * Use it to build your own representation of the document (a tree, columns, ...) faster + * than by iterating, as the walk creates no values, arrays or objects. + * + * The visitor provides these methods. Each returns an error_code: anything but SUCCESS stops + * the walk, and visit() returns it. + * + * error_code on_object_start(); + * error_code on_object_end(uint32_t member_count); + * error_code on_array_start(); + * error_code on_array_end(uint32_t element_count); + * error_code on_key(std::string_view key); // before each member value + * error_code on_string(std::string_view value); + * error_code on_int64(int64_t value, const char *raw); // integers that fit an int64_t + * error_code on_uint64(uint64_t value, const char *raw); // larger positive integers + * error_code on_double(double value, const char *raw); + * error_code on_bool(bool value); + * error_code on_null(); + * + * raw points at the number in the document, so that the visitor can tell -0 from 0, for + * example. As with the DOM parser, an integer that does not fit in 64 bits is a BIGINT_ERROR. + * + * A key or a string without escapes is a view into the document: it is valid as long as the + * document's bytes are. A key or a string with escapes is unescaped into the parser: it is + * valid until the document is iterated or visited again, or the parser parses another + * document. + * + * visit() succeeds exactly when the DOM parser does. An error may come after the visitor has + * seen part of the document. The document is rewound before and after the walk, so that it + * can be iterated afterwards. The visitor may throw: the exception goes through visit(), and + * the document must then be rewound before it is used again. + * + * To parse and visit a document in one call, faster on small documents, see parser::visit(). + * + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** * Returns debugging information. */ @@ -204690,6 +216635,9 @@ class document { simdjson_inline value_iterator resume_value_iterator() noexcept; simdjson_inline value_iterator get_root_value_iterator() noexcept; + /** The walk of visit(), between its two rewinds. */ + template + simdjson_warn_unused simdjson_inline error_code visit_root(V &visitor); simdjson_inline simdjson_result start_or_resume_object() noexcept; static simdjson_inline document start(ondemand::json_iterator &&iter) noexcept; @@ -204909,6 +216857,9 @@ struct simdjson_result : public lasx::implementation_s simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); simdjson_inline simdjson_result get_array() & noexcept; simdjson_inline simdjson_result get_object() & noexcept; @@ -208196,6 +220147,7 @@ inline std::ostream& operator<<(std::ostream& out, simdjson::simdjson_result #include +#include #if SIMDJSON_STATIC_REFLECTION #include #include @@ -208405,9 +220357,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { SIMDJSON_TRY(v.get(scratch.elements.emplace_back())); release.parsed++; } - out.reserve(release.parsed); - release.complete = true; - for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + if constexpr (std::is_trivially_copyable_v) { + out.assign(scratch.elements.begin(), scratch.elements.end()); + release.complete = true; + } else if (sizeof(value_type) <= 32 && scratch.elements.capacity() / 2 < release.parsed) { + // Hand the buffer over only when it is at least half full, so that out + // does not keep the capacity of an earlier, larger array. Swapping + // large structs is slower than moving them (recipe_book benchmark). + size_t const capacity = scratch.elements.capacity(); + out.swap(scratch.elements); + release.complete = true; + if (capacity * sizeof(value_type) <= (1 << 20)) { scratch.elements.reserve(capacity); } + } else { + out.reserve(release.parsed); + release.complete = true; + for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + } return SUCCESS; } } @@ -208637,7 +220602,11 @@ consteval void append_eligible_fields(std::meta::info type, std::vector(std::meta::substitute(^^flattenable_type, {flattened}))) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member whose type is a structure deserialized member by member", mem); +#else + simdjson::detail::flatten_requires_a_member_deserialized_member_by_member(); +#endif } append_eligible_fields(flattened, prefix, fields); } else { @@ -209993,6 +221962,27 @@ simdjson_warn_unused simdjson_inline simdjson_result value::get_number() return iter.get_number(); } +template +simdjson_warn_unused simdjson_inline error_code value::visit(V &visitor) { + if (!iter.is_at_start()) { return OUT_OF_ORDER_ITERATION; } + json_iterator &json_iter = iter.json_iter(); + const uint8_t *const json = iter.peek_start(); + // The escaped strings of the value go where reading it would put them, so that the string + // buffer has room for them however many times the value is visited. + uint8_t *const string_buf_loc = json_iter._string_buf_loc; + error_code error; + switch (*json) { + case '{': case '[': + error = json_iter.visit_container(visitor, iter.start_position(), size_t(iter.depth() - 1)); + break; + // A scalar value is nested in a container: its parser reads inside the document. + case '"': error = json_iter.visit_string(json, false, visitor); break; + default: error = json_iter.visit_scalar(json, visitor); break; + } + json_iter._string_buf_loc = string_buf_loc; + return error; +} + simdjson_inline std::string_view value::raw_json_token() noexcept { return std::string_view(reinterpret_cast(iter.peek_start()), iter.peek_start_length()); } @@ -210404,6 +222394,12 @@ simdjson_inline simdjson_result::operator bool() noexcept } #endif +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + simdjson_inline simdjson_result simdjson_result::raw_json_token() noexcept { if (error()) { return error(); } return first.raw_json_token(); @@ -210499,6 +222495,124 @@ inline void document::rewind() noexcept { static_cast(iter.rewind()); } +simdjson_warn_unused simdjson_inline error_code document::validate() noexcept { + SIMDJSON_TRY(iter.rewind()); + const bool check_trailing = !iter.streaming(); + const uint8_t first = *iter.peek(); + error_code error; + switch (first) { + case '{': case '[': + error = iter.validate_container(); + break; + case '"': + error = get_root_value_iterator().get_root_string(check_trailing, false).error(); + break; + case 't': case 'f': + error = get_root_value_iterator().get_root_bool(check_trailing).error(); + break; + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && !null_value) { error = N_ATOM_ERROR; } +#if SIMDJSON_ENABLE_NAN_INF + if (error && !get_root_value_iterator().get_root_double(check_trailing).error()) { error = SUCCESS; } +#endif + break; + } + default: + error = get_root_value_iterator().get_root_double(check_trailing).error(); + break; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit(V &visitor) { + SIMDJSON_TRY(iter.rewind()); + const error_code error = visit_root(visitor); + // The strings of the walk stay in the buffer, but an iteration may start from its beginning. + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit_root(V &visitor) { + const bool check_trailing = !iter.streaming(); + const uint8_t *const first = iter.peek(); + const char *const raw = reinterpret_cast(first); + error_code error; + switch (*first) { + case '{': case '[': + return iter.visit_container(visitor, iter.position(), 0); + case '"': { + raw_json_string text; + error = get_root_value_iterator().get_root_raw_json_string(check_trailing).get(text); + if (!error) { return iter.visit_string(first, false, visitor); } + break; + } + case 't': case 'f': { + bool value; + error = get_root_value_iterator().get_root_bool(check_trailing).get(value); + if (!error) { return visitor.on_bool(value); } + break; + } + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && null_value) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + double value; + if (!get_root_value_iterator().get_root_double(check_trailing).get(value)) { return visitor.on_double(value, raw); } +#endif + if (!error) { error = N_ATOM_ERROR; } + break; + } + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + number value; + error = get_root_value_iterator().get_root_number(check_trailing).get(value); + if (!error) { return json_iterator::visit_number(value, raw, visitor); } + break; + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': { + double value; + error = get_root_value_iterator().get_root_double(check_trailing).get(value); + if (!error) { return visitor.on_double(value, raw); } + return error == TRAILING_CONTENT ? error : TAPE_ERROR; + } +#endif + default: + return TAPE_ERROR; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (*first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + return error; +} + inline std::string document::to_debug_string() noexcept { return iter.to_string(); } @@ -211053,6 +223167,16 @@ simdjson_inline error_code simdjson_result::rewind() n first.rewind(); return SUCCESS; } +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + +simdjson_warn_unused simdjson_inline error_code simdjson_result::validate() noexcept { + if (error()) { return error(); } + return first.validate(); +} simdjson_inline simdjson_result simdjson_result::begin() & noexcept { if (error()) { return error(); } return first.begin(); @@ -212123,6 +224247,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } worker->start_thread(); @@ -212376,6 +224501,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch @@ -212391,6 +224519,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -212732,6 +224863,8 @@ simdjson_inline simdjson_result simdjson_result= 8; src += 8, len -= 8) { + std::memcpy(&word, src, sizeof(word)); + word ^= BACKSLASHES; + if ((word - ONES) & ~word & HIGHS) { return true; } + } + uint64_t keep; + std::memcpy(&keep, KEEP + 8 - len, sizeof(keep)); + std::memcpy(&word, src, sizeof(word)); + word = (word ^ BACKSLASHES) | ~keep; + return ((word - ONES) & ~word & HIGHS) != 0; +} + +simdjson_warn_unused simdjson_never_inline error_code json_iterator::validate_container() noexcept { + const uint8_t *const json = token.buf; + token_position pos = token.position(); + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // One bit per depth tells whether the container at that depth is an array. Deeper than + // the fixed stack allows, the bits move to the heap. + uint64_t fixed_stack[16]{}; + std::unique_ptr heap_stack; + uint64_t *is_array = fixed_stack; + size_t depth = 0; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VALIDATE_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VALIDATE_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': goto scalar_string; + default: goto scalar; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. Its bit may then + // be at max_depth, which the stack has room for. + if (++depth >= max_depth && (pos == end || json[*pos] != c + 2)) { return DEPTH_ERROR; } + // The bits move once: the next time this depth is reached, the heap holds the current + // bits and the fixed stack holds stale ones. + if (depth == sizeof(fixed_stack) * 8 && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint64_t[max_depth / 64 + 1]()); + if (!heap_stack) { return MEMALLOC; } + std::memcpy(heap_stack.get(), fixed_stack, sizeof(fixed_stack)); + is_array = heap_stack.get(); + } + if (c == '[') { + is_array[depth / 64] |= uint64_t(1) << (depth % 64); + SIMDJSON_VALIDATE_NEXT(); + if (c == ']') { goto container_end; } + goto value; + } + is_array[depth / 64] &= ~(uint64_t(1) << (depth % 64)); + SIMDJSON_VALIDATE_NEXT(); + if (c == '}') { goto container_end; } + goto key; + +key: + if (c != '"') { return TAPE_ERROR; } + // A string is valid once stage 1 has accepted the document, unless it holds an escape. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + SIMDJSON_VALIDATE_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VALIDATE_NEXT(); + goto value; + +scalar_string: + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + goto value_end; + +scalar: + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + break; + default: + return TAPE_ERROR; + } + // The scalar is not the last token, so the parsers read inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + switch (c) { + case 't': if (!atomparsing::is_valid_true_atom(json + index)) { return T_ATOM_ERROR; } break; + case 'f': if (!atomparsing::is_valid_false_atom(json + index)) { return F_ATOM_ERROR; } break; + case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (!atomparsing::is_valid_null_atom(json + index) && !atomparsing::is_valid_nan_atom(json + index)) { return N_ATOM_ERROR; } +#else + if (!atomparsing::is_valid_null_atom(json + index)) { return N_ATOM_ERROR; } +#endif + break; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': if (!atomparsing::is_valid_nan_atom(json + index)) { return TAPE_ERROR; } break; + case 'i': case 'I': if (!atomparsing::is_valid_inf_atom(json + index)) { return TAPE_ERROR; } break; +#endif + default: + if (numberparsing::parse_double(json + index).error()) { return NUMBER_ERROR; } + break; + } + +value_end: + SIMDJSON_VALIDATE_NEXT(); + if (c == ',') { + SIMDJSON_VALIDATE_NEXT(); + if (is_array[depth / 64] & (uint64_t(1) << (depth % 64))) { goto value; } + goto key; + } + if (c != (is_array[depth / 64] & (uint64_t(1) << (depth % 64)) ? ']' : '}')) { return TAPE_ERROR; } + +container_end: + if (--depth > 0) { goto value_end; } +#undef SIMDJSON_VALIDATE_NEXT + if (!streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_number(const number &value, const char *raw, V &visitor) { + switch (value.get_number_type()) { + case number_type::signed_integer: return visitor.on_int64(value.get_int64(), raw); + case number_type::unsigned_integer: return visitor.on_uint64(value.get_uint64(), raw); + case number_type::floating_point_number: return visitor.on_double(value.get_double(), raw); + default: return BIGINT_ERROR; + } +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_string(const uint8_t *quote, bool key, V &visitor) { + const uint8_t *const start = quote + 1; + // A string without escapes is passed as it is in the document. + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (const uint8_t *src = start;; src += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(src, scratch); + if (bs_quote.has_quote_first()) { + std::string_view text(reinterpret_cast(start), size_t(src - start) + size_t(bs_quote.quote_index())); + return key ? visitor.on_key(text) : visitor.on_string(text); + } + if (bs_quote.has_backslash()) { break; } + } + uint8_t *const end = parser->implementation->parse_string(start, _string_buf_loc, false); + if (!end) { return STRING_ERROR; } + std::string_view text(reinterpret_cast(_string_buf_loc), size_t(end - _string_buf_loc)); + _string_buf_loc = end; + return key ? visitor.on_key(text) : visitor.on_string(text); +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_scalar(const uint8_t *src, V &visitor) { + switch (*src) { + case 't': return atomparsing::is_valid_true_atom(src) ? visitor.on_bool(true) : T_ATOM_ERROR; + case 'f': return atomparsing::is_valid_false_atom(src) ? visitor.on_bool(false) : F_ATOM_ERROR; + case 'n': + if (atomparsing::is_valid_null_atom(src)) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } +#endif + return N_ATOM_ERROR; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + number value; + SIMDJSON_TRY(numberparsing::parse_number(src, value)); + return visit_number(value, reinterpret_cast(src), visitor); + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } + return TAPE_ERROR; + case 'i': case 'I': + if (atomparsing::is_valid_inf_atom(src)) { return visitor.on_double(std::numeric_limits::infinity(), reinterpret_cast(src)); } + return TAPE_ERROR; +#endif + default: + return TAPE_ERROR; + } +} + +template +simdjson_warn_unused error_code json_iterator::visit_container(V &visitor, token_position start, size_t parent_depth) { + const uint8_t *const json = token.buf; + token_position pos = start; + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // For each open container, the number of its elements so far, with the top bit set for an + // array. Deeper than the fixed stack allows, the stack moves to the heap. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + constexpr size_t FIXED_DEPTH = 64; + uint32_t fixed_stack[FIXED_DEPTH]; + std::unique_ptr heap_stack; + uint32_t *stack = fixed_stack; + size_t depth = parent_depth; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VISIT_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VISIT_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': + // A string is not the last token, so that its closing quote is inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, false, visitor)); + goto value_end; + default: + // The scalar is not the last token, so the parsers read inside the document. + if (simdjson_unlikely(pos == end)) { + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + return INCOMPLETE_ARRAY_OR_OBJECT; + default: + return TAPE_ERROR; + } + } + SIMDJSON_TRY(visit_scalar(json + index, visitor)); + goto value_end; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. + if (pos != end && json[*pos] == c + 2) { + pos++; + if (c == '[') { + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_TRY(visitor.on_array_end(0)); + } else { + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_TRY(visitor.on_object_end(0)); + } + if (depth == parent_depth) { goto document_end; } + goto value_end; + } + if (++depth >= max_depth) { return DEPTH_ERROR; } + // Copy the fixed stack once. A later container at this depth must keep the + // counts already stored on the heap. + if (depth >= FIXED_DEPTH && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint32_t[max_depth]); + if (!heap_stack) { return MEMALLOC; } + // Only the slots past the parent were written. + if (parent_depth + 1 < FIXED_DEPTH) { + std::memcpy(heap_stack.get() + parent_depth + 1, fixed_stack + parent_depth + 1, (FIXED_DEPTH - parent_depth - 1) * sizeof(fixed_stack[0])); + } + stack = heap_stack.get(); + } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_VISIT_NEXT(); + goto value; + } + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_VISIT_NEXT(); + +key: + if (c != '"') { return TAPE_ERROR; } + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, true, visitor)); + SIMDJSON_VISIT_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VISIT_NEXT(); + goto value; + +value_end: + SIMDJSON_VISIT_NEXT(); + if (c == ',') { + stack[depth]++; + SIMDJSON_VISIT_NEXT(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_object_end(stack[depth])); + } + if (--depth > parent_depth) { goto value_end; } + +document_end: +#undef SIMDJSON_VISIT_NEXT + if (parent_depth == 0 && !streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + simdjson_inline bool json_iterator::at_root() const noexcept { return position() == root_position(); } @@ -213372,10 +225834,20 @@ simdjson_warn_unused simdjson_inline bool json_iterator::copy_to_buffer(const ui // peek_root_length() stops at the next structural index. Stage 1 omits the // comma or RS (0x1E) that separates stream documents, so that byte and the // whitespace around it remain in the span. RS is not a valid number finisher. + // Outside of a stream, the comma and RS are not separators: some kernels + // keep RS in the scalar token, and dropping it would accept "1\x1e". while (max_len > 0) { const uint8_t last = json[max_len - 1]; + // iterate_allow_incomplete_json() reuses _streaming, so a root scalar + // there is not a document_stream. +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + const bool separator = _streaming && !_allow_incomplete_json && + (last == ',' || last == 0x1E); +#else + const bool separator = _streaming && (last == ',' || last == 0x1E); +#endif if (last != ' ' && last != '\t' && last != '\n' && last != '\r' && - last != ',' && last != 0x1E) { + !separator) { break; } max_len--; @@ -214805,22 +227277,22 @@ simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capa return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - std::unique_ptr new_string_buf(new (std::nothrow) uint8_t[string_capacity]); - if (!new_string_buf) { return MEMALLOC; } + simdjson::internal::allocated_array new_string_buf; + if (!new_string_buf.allocate(string_capacity, _allocator)) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr new_start_positions(new (std::nothrow) token_position[new_max_depth]); if (!new_start_positions) { return MEMALLOC; } #endif - if (implementation) { - error_code err = implementation->allocate(new_capacity, new_max_depth); - if (err) { return err; } - } else { - error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, new_max_depth, implementation); if (err) { implementation.reset(); return err; } } + implementation->allocator = _allocator; + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } string_buf = std::move(new_string_buf); #if SIMDJSON_DEVELOPMENT_CHECKS start_positions = std::move(new_start_positions); @@ -214849,9 +227321,42 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iterate(p // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return document::start({ reinterpret_cast(json.data()), this }); } +// Removes from the structural indexes each comma that follows a value and +// precedes a closing bracket, so that the iterator never sees it. The entries +// past the last index (stage 1 keeps up to three there) move with the others. +#if SIMDJSON_ALLOW_TRAILING_COMMAS +simdjson_inline void parser::drop_trailing_commas(const uint8_t *buf) noexcept { + uint32_t *indexes = implementation->structural_indexes.get(); + const uint32_t n = implementation->n_structural_indexes; + uint32_t kept = 0; + uint8_t previous = '['; + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = buf[indexes[i]]; + if (c == ',' && i + 1 < n && previous != '[' && previous != '{' && previous != ',' && previous != ':') { + const uint8_t next = buf[indexes[i + 1]]; + if (next == ']' || next == '}') { + previous = c; + continue; + } + } + indexes[kept++] = indexes[i]; + previous = c; + } + if (kept != n) { + indexes[kept] = indexes[n]; + indexes[kept + 1] = indexes[n + 1]; + indexes[kept + 2] = indexes[n + 2]; + implementation->n_structural_indexes = kept; + } +} +#endif // SIMDJSON_ALLOW_TRAILING_COMMAS + #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_warn_unused simdjson_inline simdjson_result parser::iterate_allow_incomplete_json(padded_string_view json) & noexcept { if (!json.has_sufficient_padding()) { return INSUFFICIENT_PADDING; } @@ -214955,9 +227460,210 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iter // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return json_iterator(reinterpret_cast(json.data()), this); } +namespace { +struct ignoring_visitor { + simdjson_inline error_code on_object_start() { return SUCCESS; } + simdjson_inline error_code on_object_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_array_start() { return SUCCESS; } + simdjson_inline error_code on_array_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_key(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_string(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_int64(int64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_uint64(uint64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_double(double, const char *) { return SUCCESS; } + simdjson_inline error_code on_bool(bool) { return SUCCESS; } + simdjson_inline error_code on_null() { return SUCCESS; } +}; +} // unnamed namespace + +template +simdjson_warn_unused simdjson_inline error_code parser::visit(padded_string_view json, V &visitor) & { +#if !SIMDJSON_ENABLE_NAN_INF && !SIMDJSON_ALLOW_TRAILING_COMMAS + if (json.length() <= MAX_ONE_PASS_VISIT && json.has_sufficient_padding()) { + if (capacity() < json.length() || !string_buf) { + SIMDJSON_TRY( allocate(json.length(), max_depth()) ); + } + bool visitor_failed = false; + const error_code error = visit_one_pass(reinterpret_cast(json.data()), json.length(), visitor, visitor_failed); + if (error != UNINITIALIZED) { + if (error != TAPE_ERROR || visitor_failed) { return error; } + // The visitor has already seen part of the document: the regular walk only finds the + // error code, and never calls the visitor a second time. + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + ignoring_visitor ignoring; + const error_code regular_error = doc.visit(ignoring); + return regular_error ? regular_error : TAPE_ERROR; + } + } +#endif + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + return doc.visit(visitor); +} + +// A single pass over the bytes, for small documents. The root must be an array or an object, and +// the last byte that is not whitespace must be ] or }: before it, runs of whitespace, digits or +// atoms stop without a bound check. Only a closing bracket or a string may reach the end. +template +simdjson_warn_unused simdjson_inline error_code parser::visit_one_pass(const uint8_t *const buf, const size_t len, V &visitor, bool &visitor_failed) { + const auto is_whitespace = [](uint8_t c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; + if (len == 0 || len > MAX_ONE_PASS_VISIT) { return UNINITIALIZED; } + const uint8_t *p = buf; + const uint8_t *last = buf + len - 1; + while (p < last && is_whitespace(*p)) { p++; } + while (last > p && is_whitespace(*last)) { last--; } + if ((*p != '{' && *p != '[') || (*last != '}' && *last != ']')) { return UNINITIALIZED; } + const uint8_t *const end = last + 1; + uint8_t *dst = string_buf.get(); + bool non_ascii = false; + // For each open container, the number of its elements so far, with the top bit set for an + // array. Each container opens at a distinct byte before the last one, so that the depth stays + // below MAX_ONE_PASS_VISIT. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + uint32_t stack[MAX_ONE_PASS_VISIT]; + size_t depth = 0; + uint8_t c = *p; + +#define SIMDJSON_ONE_PASS_CALL(EXPR) \ + do { \ + const error_code one_pass_error = (EXPR); \ + if (simdjson_unlikely(one_pass_error != SUCCESS)) { visitor_failed = true; return one_pass_error; } \ + } while (0) +#define SIMDJSON_ONE_PASS_WHITESPACE() while (is_whitespace(*p)) { p++; } +// The string at p, which is left past the closing quote. +#define SIMDJSON_ONE_PASS_STRING(METHOD) \ + do { \ + const uint8_t *const start = ++p; \ + bool escaped = false; \ + for (;; p++) { \ + if (simdjson_unlikely(p >= end)) { return TAPE_ERROR; } \ + if (*p == '"') { break; } \ + if (*p == '\\') { \ + escaped = true; \ + p++; \ + } else if (simdjson_unlikely(*p < 0x20)) { \ + return TAPE_ERROR; \ + } else if (*p >= 0x80) { \ + non_ascii = true; \ + } \ + } \ + std::string_view text(reinterpret_cast(start), size_t(p - start)); \ + p++; \ + if (escaped) { \ + uint8_t *const unescaped_end = implementation->parse_string(start, dst, false); \ + if (unescaped_end == nullptr) { return TAPE_ERROR; } \ + text = std::string_view(reinterpret_cast(dst), size_t(unescaped_end - dst)); \ + dst = unescaped_end; \ + } \ + SIMDJSON_ONE_PASS_CALL(visitor.METHOD(text)); \ + } while (0) + + goto container_start; + +value: + switch (*p) { + case '{': case '[': + c = *p; + goto container_start; + case '"': + SIMDJSON_ONE_PASS_STRING(on_string); + goto value_end; + case 't': + if (!atomparsing::is_valid_true_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(true)); + p += 4; + goto value_end; + case 'f': + if (!atomparsing::is_valid_false_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(false)); + p += 5; + goto value_end; + case 'n': + if (!atomparsing::is_valid_null_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_null()); + p += 4; + goto value_end; + default: { + number value; + if (numberparsing::parse_number(p, value) != SUCCESS) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(json_iterator::visit_number(value, reinterpret_cast(p), visitor)); + while (jsoncharutils::is_not_structural_or_whitespace(*p)) { p++; } + goto value_end; + } + } + +container_start: + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + // As in DOM, an empty container does not count toward the maximal depth. + if (*p == c + 2) { + p++; + if (c == '[') { + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(0)); + } else { + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(0)); + } + if (depth == 0) { goto document_end; } + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + if (++depth >= max_depth()) { return TAPE_ERROR; } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + goto value; + } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + +key: + if (*p != '"') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_STRING(on_key); + SIMDJSON_ONE_PASS_WHITESPACE(); + if (*p != ':') { return TAPE_ERROR; } + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + goto value; + +value_end: + SIMDJSON_ONE_PASS_WHITESPACE(); + c = *p++; + if (c == ',') { + stack[depth]++; + SIMDJSON_ONE_PASS_WHITESPACE(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(stack[depth])); + } + if (--depth > 0) { + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + +document_end: +#undef SIMDJSON_ONE_PASS_CALL +#undef SIMDJSON_ONE_PASS_WHITESPACE +#undef SIMDJSON_ONE_PASS_STRING + if (p != end) { return TAPE_ERROR; } + if (non_ascii && !simdjson::validate_utf8(reinterpret_cast(buf), len)) { return TAPE_ERROR; } + return SUCCESS; +} + inline simdjson_result parser::iterate_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept { if(batch_size < MINIMAL_BATCH_SIZE) { batch_size = MINIMAL_BATCH_SIZE; } if((len >= 3) && (std::memcmp(buf, "\xEF\xBB\xBF", 3) == 0)) { @@ -215075,6 +227781,13 @@ simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return _max_depth; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} + simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept { if(max_capacity > dom::MINIMAL_DOCUMENT_CAPACITY) { _max_capacity = max_capacity; @@ -215594,13 +228307,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_objec _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing } at end"); } - // If the last character is } *and* the first gibberish character is also '}' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is } *and* the first gibberish character is '}', ']' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == '}') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed object. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -216004,13 +228719,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_array _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing ] at end"); } - // If the last character is ] *and* the first gibberish character is also ']' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is ] *and* the first gibberish character is ']', '}' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == ']') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed array. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -216180,7 +228897,7 @@ simdjson_inline simdjson_result value_iterator::get_root_numb // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -216204,7 +228921,7 @@ simdjson_inline simdjson_result value_iterator::get_root_number(bool che // number: -0.e-308. // NOTE: the current approach doesn't work for very big integer numbers containing more than 1074 digits. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -216286,7 +229003,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::g simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer tmpbuf[20+1] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+1)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 20 characters"); @@ -216303,7 +229020,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::ge simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64_in_string(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer tmpbuf[20+2] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+2)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 22 characters"); @@ -216324,7 +229041,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -216346,7 +229063,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -216368,7 +229085,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ // digits that matter is smaller for binary32, but the JSON document may still // spell out a long number that we must parse (and round) faithfully. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -216387,7 +229104,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ auto max_len = peek_root_length(); auto json = peek_root_scalar("float"); // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -216725,6 +229442,9 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '"': return json_type::string; case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } +#endif return json_type::null; case 't': case 'f': return json_type::boolean; @@ -216732,6 +229452,14 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return json_type::number; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; + case 'I': case 'i': + if (atomparsing::is_valid_inf_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; +#endif default: return json_type::unknown; } @@ -217980,6 +230708,14 @@ namespace simd { simdjson_inline simd8() : simd8(zero()) {} simdjson_inline simd8(const uint8_t values[VL8]) : simd8(load(values)) {} simdjson_inline simd8(uint8_t _value) : simd8(splat(_value)) {} + // The n < VL8 bytes at ptr followed by fill bytes. Reads no byte outside [ptr, ptr + n). + static simdjson_inline simd8 load_partial(const uint8_t *ptr, size_t n, const uint8_t *begin, uint8_t fill) { + (void)begin; + uint8_t block[VL8]; + std::memset(block, fill, VL8); + std::memcpy(block, ptr, n); + return load(block); + } simdjson_inline simd8(simd8 mask) : value(__riscv_vmerge_vxm_u8m1(zero(), -1, (vbool_t)mask, VL8)) {} simdjson_inline operator const vuint8_t&() const { return this->value; } @@ -218316,6 +231052,7 @@ simdjson_inline backslash_and_quote backslash_and_quote::copy_and_find(const uin /* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ /* amalgamation skipped (editor-only): #include "simdjson/rvv-vls/base.h" */ /* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing_tables.h" */ +/* amalgamation skipped (editor-only): #include "simdjson/internal/numberparsing.h" */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include @@ -218331,7 +231068,6 @@ namespace simdjson { namespace rvv_vls { namespace numberparsing { -// credit: https://johnnylee-sde.github.io/Fast-numeric-string-to-int/ /** @private */ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { uint64_t val; @@ -218340,9 +231076,7 @@ static simdjson_inline uint32_t parse_eight_digits_unrolled(const char *chars) { #else val = __riscv_vmv_x(__riscv_vreinterpret_u64m1(__riscv_vlmul_ext_u8m1(__riscv_vle8_v_u8mf2((uint8_t*)chars, 8)))); #endif - val = (val & 0x0F0F0F0F0F0F0F0F) * 2561 >> 8; - val = (val & 0x00FF00FF00FF00FF) * 6553601 >> 16; - return uint32_t((val & 0x0000FFFF0000FFFF) * 42949672960001 >> 32); + return internal::parse_eight_digits_swar(val); } /** @private */ @@ -219809,6 +232543,23 @@ class value { */ simdjson_inline std::string_view raw_json_token() noexcept; + /** + * Calls the visitor for this value and everything in it, as document::visit() does for a + * whole document, for example after navigating to a field: + * + * auto error = doc["payload"].visit(visitor); + * + * The value must not have been read. The walk does not move the iterator: to go on, read the + * value or the next field or element as usual. A string with escapes is valid until you read + * the document further or visit again. The maximal depth counts from the root of the document. + * A value at the root also fails if anything follows it. + * + * @returns SUCCESS, OUT_OF_ORDER_ITERATION if the value has been read, the first error found + * in the value, or the first error the visitor returns. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); + /** * Get a string_view pointing at this value in the JSON document. * If this element is an array or an object, it consumes the array or the object @@ -220126,6 +232877,8 @@ struct simdjson_result : public rvv_vls::implementatio /** @copydoc simdjson_inline std::string_view value::raw_json_token() const noexcept */ simdjson_inline simdjson_result raw_json_token() noexcept; simdjson_inline simdjson_result raw_json() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** @copydoc simdjson_inline simdjson_result current_location() noexcept */ simdjson_inline simdjson_result current_location() noexcept; @@ -220471,6 +233224,29 @@ class json_iterator { simdjson_inline error_code out_of_place_error() noexcept; /** Tells whether the string before pos, followed by a colon, is a key. */ static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; + /** + * Validates the array or object at the current position and everything in it, without + * recursion. Outside of streaming mode, it also checks that nothing follows it. It does + * not move the iterator. + */ + simdjson_warn_unused error_code validate_container() noexcept; + static simdjson_inline bool has_backslash(const uint8_t *src, size_t len) noexcept; + /** + * Calls the visitor for the array or object at the start position and everything in it, + * without recursion (see document::visit()). The container is at depth parent_depth + 1. At + * the root (parent_depth == 0) and outside of streaming mode, it also checks that nothing + * follows it. It does not move the iterator. Escaped strings are copied into the string + * buffer. + */ + template + simdjson_warn_unused error_code visit_container(V &visitor, token_position start, size_t parent_depth); + template + simdjson_warn_unused simdjson_inline error_code visit_string(const uint8_t *quote, bool key, V &visitor); + template + simdjson_warn_unused simdjson_inline error_code visit_scalar(const uint8_t *src, V &visitor); + /** Calls the visitor for a number that numberparsing::parse_number accepted. */ + template + static simdjson_warn_unused simdjson_inline error_code visit_number(const number &value, const char *raw, V &visitor); /** * Tell whether the iterator is still at the start @@ -220660,7 +233436,8 @@ class json_iterator { /** * Take an input in json containing max_len characters and attempt to copy it over to tmpbuf, a buffer with * N bytes of capacity. It will return false if N is too small (smaller than max_len) of if it is zero. - * Trailing whitespace, commas, and record separators (0x1E) do not count toward max_len. + * Trailing whitespace does not count toward max_len. A comma or record + * separator (0x1E) is ignored only for a document stream. * The buffer (tmpbuf) is padded with space characters. */ simdjson_warn_unused simdjson_inline bool copy_to_buffer(const uint8_t *json, uint32_t max_len, uint8_t *tmpbuf, size_t N) noexcept; @@ -221356,6 +234133,33 @@ class parser { */ simdjson_warn_unused simdjson_result iterate_raw(padded_string_view json) & noexcept; + /** + * Parses the document and walks it once with the visitor: the same as iterate() followed by + * document::visit(), with the same values and, when the visitor returns SUCCESS, the same + * error code, but faster on small documents. + * + * counting_visitor visitor; + * auto error = parser.visit(R"({"stars":[1,2,3]})"_padded, visitor); + * + * A document of at most MAX_ONE_PASS_VISIT bytes whose root is an object or an array is read in + * a single pass, without the structural index that iterate() builds. Some checks, such as the + * UTF-8 validation, then come at the end of the walk: on an invalid document, the visitor may + * have seen part or all of it before visit() returns the error code of document::visit(), and + * an error returned by the visitor may come first. With SIMDJSON_ENABLE_NAN_INF or + * SIMDJSON_ALLOW_TRAILING_COMMAS, there is no one-pass walk. + * + * See document::visit() for the methods of the visitor and the lifetime of the strings. + * + * @param json The JSON to parse, with at least SIMDJSON_PADDING bytes after it. + * @param visitor The visitor. + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(padded_string_view json, V &visitor) &; + /** Documents of at most this many bytes may be visited in one pass, see visit(). */ + static constexpr size_t MAX_ONE_PASS_VISIT = 32; + /** * Parse a buffer containing many JSON documents. @@ -221514,6 +234318,20 @@ class parser { */ simdjson_pure simdjson_inline size_t max_depth() const noexcept; + /** + * Route the allocation of the buffers that grow with the largest document + * (the string buffer and the structural indexes) through a buffer_allocator. + * nullptr, the default, uses new[]. The allocator must outlive the parser. + * + * Buffers that the parser already holds keep the allocator that allocated + * them until the parser grows them, so set the allocator before the first + * document or the first call to allocate(). A failed allocation makes the + * parser return MEMALLOC and leaves its buffers as they were. + */ + simdjson_inline void set_allocator(const buffer_allocator *allocator) noexcept; + /** The buffer_allocator set by set_allocator(), or nullptr. */ + simdjson_pure simdjson_inline const buffer_allocator *get_allocator() const noexcept; + /** * Ensure this parser has enough memory to process JSON documents up to `capacity` bytes in length * and `max_depth` depth. @@ -221623,17 +234441,27 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr& get_threadlocal_parser_if_exists(); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + simdjson_inline void drop_trailing_commas(const uint8_t *buf) noexcept; +#endif #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** + * The one-pass walk of visit(). Returns UNINITIALIZED when it does not handle the document, + * and TAPE_ERROR when the document is invalid. visitor_failed tells an error of the visitor. + */ + template + simdjson_warn_unused simdjson_inline error_code visit_one_pass(const uint8_t *buf, size_t len, V &visitor, bool &visitor_failed); /** @private [for benchmarking access] The implementation to use */ std::unique_ptr implementation{}; size_t _capacity{0}; size_t _max_capacity; size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; - std::unique_ptr string_buf{}; + simdjson::internal::allocated_array string_buf{}; + const buffer_allocator *_allocator{nullptr}; #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; @@ -222891,6 +235719,58 @@ class document { * left as is. */ inline void rewind() noexcept; + /** + * Validates the whole document: its structure, every string (escapes included), every + * number, true, false and null, and that nothing follows the root value. Strings are + * checked as get_string() checks them and numbers as get_double() does. The document is + * rewound before and after, so that it can be iterated after a successful validation. + * + * It is faster than iterating through every value, because it walks the tokens directly, + * without creating values, arrays or objects. + * + * @returns SUCCESS if the document is valid, or the error found first. + */ + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + /** + * Walks the whole document once and calls the visitor for each value, in document order. + * Use it to build your own representation of the document (a tree, columns, ...) faster + * than by iterating, as the walk creates no values, arrays or objects. + * + * The visitor provides these methods. Each returns an error_code: anything but SUCCESS stops + * the walk, and visit() returns it. + * + * error_code on_object_start(); + * error_code on_object_end(uint32_t member_count); + * error_code on_array_start(); + * error_code on_array_end(uint32_t element_count); + * error_code on_key(std::string_view key); // before each member value + * error_code on_string(std::string_view value); + * error_code on_int64(int64_t value, const char *raw); // integers that fit an int64_t + * error_code on_uint64(uint64_t value, const char *raw); // larger positive integers + * error_code on_double(double value, const char *raw); + * error_code on_bool(bool value); + * error_code on_null(); + * + * raw points at the number in the document, so that the visitor can tell -0 from 0, for + * example. As with the DOM parser, an integer that does not fit in 64 bits is a BIGINT_ERROR. + * + * A key or a string without escapes is a view into the document: it is valid as long as the + * document's bytes are. A key or a string with escapes is unescaped into the parser: it is + * valid until the document is iterated or visited again, or the parser parses another + * document. + * + * visit() succeeds exactly when the DOM parser does. An error may come after the visitor has + * seen part of the document. The document is rewound before and after the walk, so that it + * can be iterated afterwards. The visitor may throw: the exception goes through visit(), and + * the document must then be rewound before it is used again. + * + * To parse and visit a document in one call, faster on small documents, see parser::visit(). + * + * @returns SUCCESS, the first error found in the document, or the first error the visitor + * returned. + */ + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); /** * Returns debugging information. */ @@ -223061,6 +235941,9 @@ class document { simdjson_inline value_iterator resume_value_iterator() noexcept; simdjson_inline value_iterator get_root_value_iterator() noexcept; + /** The walk of visit(), between its two rewinds. */ + template + simdjson_warn_unused simdjson_inline error_code visit_root(V &visitor); simdjson_inline simdjson_result start_or_resume_object() noexcept; static simdjson_inline document start(ondemand::json_iterator &&iter) noexcept; @@ -223280,6 +236163,9 @@ struct simdjson_result : public rvv_vls::implementa simdjson_inline simdjson_result(error_code error) noexcept; ///< @private simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; + simdjson_warn_unused simdjson_inline error_code validate() noexcept; + template + simdjson_warn_unused simdjson_inline error_code visit(V &visitor); simdjson_inline simdjson_result get_array() & noexcept; simdjson_inline simdjson_result get_object() & noexcept; @@ -226567,6 +239453,7 @@ inline std::ostream& operator<<(std::ostream& out, simdjson::simdjson_result #include +#include #if SIMDJSON_STATIC_REFLECTION #include #include @@ -226776,9 +239663,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { SIMDJSON_TRY(v.get(scratch.elements.emplace_back())); release.parsed++; } - out.reserve(release.parsed); - release.complete = true; - for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + if constexpr (std::is_trivially_copyable_v) { + out.assign(scratch.elements.begin(), scratch.elements.end()); + release.complete = true; + } else if (sizeof(value_type) <= 32 && scratch.elements.capacity() / 2 < release.parsed) { + // Hand the buffer over only when it is at least half full, so that out + // does not keep the capacity of an earlier, larger array. Swapping + // large structs is slower than moving them (recipe_book benchmark). + size_t const capacity = scratch.elements.capacity(); + out.swap(scratch.elements); + release.complete = true; + if (capacity * sizeof(value_type) <= (1 << 20)) { scratch.elements.reserve(capacity); } + } else { + out.reserve(release.parsed); + release.complete = true; + for (auto &e : scratch.elements) { out.emplace_back(std::move(e)); } + } return SUCCESS; } } @@ -227008,7 +239908,11 @@ consteval void append_eligible_fields(std::meta::info type, std::vector(std::meta::substitute(^^flattenable_type, {flattened}))) { +#if defined(__cpp_exceptions) throw std::meta::exception(u8"simdjson::flatten requires a member whose type is a structure deserialized member by member", mem); +#else + simdjson::detail::flatten_requires_a_member_deserialized_member_by_member(); +#endif } append_eligible_fields(flattened, prefix, fields); } else { @@ -228364,6 +241268,27 @@ simdjson_warn_unused simdjson_inline simdjson_result value::get_number() return iter.get_number(); } +template +simdjson_warn_unused simdjson_inline error_code value::visit(V &visitor) { + if (!iter.is_at_start()) { return OUT_OF_ORDER_ITERATION; } + json_iterator &json_iter = iter.json_iter(); + const uint8_t *const json = iter.peek_start(); + // The escaped strings of the value go where reading it would put them, so that the string + // buffer has room for them however many times the value is visited. + uint8_t *const string_buf_loc = json_iter._string_buf_loc; + error_code error; + switch (*json) { + case '{': case '[': + error = json_iter.visit_container(visitor, iter.start_position(), size_t(iter.depth() - 1)); + break; + // A scalar value is nested in a container: its parser reads inside the document. + case '"': error = json_iter.visit_string(json, false, visitor); break; + default: error = json_iter.visit_scalar(json, visitor); break; + } + json_iter._string_buf_loc = string_buf_loc; + return error; +} + simdjson_inline std::string_view value::raw_json_token() noexcept { return std::string_view(reinterpret_cast(iter.peek_start()), iter.peek_start_length()); } @@ -228775,6 +241700,12 @@ simdjson_inline simdjson_result::operator bool() noexc } #endif +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + simdjson_inline simdjson_result simdjson_result::raw_json_token() noexcept { if (error()) { return error(); } return first.raw_json_token(); @@ -228870,6 +241801,124 @@ inline void document::rewind() noexcept { static_cast(iter.rewind()); } +simdjson_warn_unused simdjson_inline error_code document::validate() noexcept { + SIMDJSON_TRY(iter.rewind()); + const bool check_trailing = !iter.streaming(); + const uint8_t first = *iter.peek(); + error_code error; + switch (first) { + case '{': case '[': + error = iter.validate_container(); + break; + case '"': + error = get_root_value_iterator().get_root_string(check_trailing, false).error(); + break; + case 't': case 'f': + error = get_root_value_iterator().get_root_bool(check_trailing).error(); + break; + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && !null_value) { error = N_ATOM_ERROR; } +#if SIMDJSON_ENABLE_NAN_INF + if (error && !get_root_value_iterator().get_root_double(check_trailing).error()) { error = SUCCESS; } +#endif + break; + } + default: + error = get_root_value_iterator().get_root_double(check_trailing).error(); + break; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit(V &visitor) { + SIMDJSON_TRY(iter.rewind()); + const error_code error = visit_root(visitor); + // The strings of the walk stay in the buffer, but an iteration may start from its beginning. + static_cast(iter.rewind()); + return error; +} + +template +simdjson_warn_unused simdjson_inline error_code document::visit_root(V &visitor) { + const bool check_trailing = !iter.streaming(); + const uint8_t *const first = iter.peek(); + const char *const raw = reinterpret_cast(first); + error_code error; + switch (*first) { + case '{': case '[': + return iter.visit_container(visitor, iter.position(), 0); + case '"': { + raw_json_string text; + error = get_root_value_iterator().get_root_raw_json_string(check_trailing).get(text); + if (!error) { return iter.visit_string(first, false, visitor); } + break; + } + case 't': case 'f': { + bool value; + error = get_root_value_iterator().get_root_bool(check_trailing).get(value); + if (!error) { return visitor.on_bool(value); } + break; + } + case 'n': { + bool null_value; + error = get_root_value_iterator().is_root_null(check_trailing).get(null_value); + if (!error && null_value) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + double value; + if (!get_root_value_iterator().get_root_double(check_trailing).get(value)) { return visitor.on_double(value, raw); } +#endif + if (!error) { error = N_ATOM_ERROR; } + break; + } + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': { + number value; + error = get_root_value_iterator().get_root_number(check_trailing).get(value); + if (!error) { return json_iterator::visit_number(value, raw, visitor); } + break; + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': { + double value; + error = get_root_value_iterator().get_root_double(check_trailing).get(value); + if (!error) { return visitor.on_double(value, raw); } + return error == TRAILING_CONTENT ? error : TAPE_ERROR; + } +#endif + default: + return TAPE_ERROR; + } + // The root getters report a scalar of the wrong kind as INCORRECT_TYPE. + if (error == INCORRECT_TYPE) { + switch (*first) { + case 't': error = T_ATOM_ERROR; break; + case 'f': error = F_ATOM_ERROR; break; + case 'n': error = N_ATOM_ERROR; break; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error = NUMBER_ERROR; break; + default: error = TAPE_ERROR; break; + } + } + return error; +} + inline std::string document::to_debug_string() noexcept { return iter.to_string(); } @@ -229424,6 +242473,16 @@ simdjson_inline error_code simdjson_result::rewind( first.rewind(); return SUCCESS; } +template +simdjson_warn_unused simdjson_inline error_code simdjson_result::visit(V &visitor) { + if (error()) { return error(); } + return first.visit(visitor); +} + +simdjson_warn_unused simdjson_inline error_code simdjson_result::validate() noexcept { + if (error()) { return error(); } + return first.validate(); +} simdjson_inline simdjson_result simdjson_result::begin() & noexcept { if (error()) { return error(); } return first.begin(); @@ -230494,6 +243553,7 @@ inline void document_stream::start() noexcept { // load_from_stage1_thread() swaps *parser with stage1_thread_parser, which // then parses every other batch: give it the same settings. stage1_thread_parser.set_max_capacity(parser->max_capacity()); + stage1_thread_parser.set_allocator(parser->get_allocator()); error = stage1_thread_parser.allocate(batch_size, parser->max_depth()); if (error) { return; } worker->start_thread(); @@ -230747,6 +243807,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch @@ -230762,6 +243825,9 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch break; } error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + if (!err) { p.drop_trailing_commas(&buf[_batch_start]); } +#endif return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -231103,6 +244169,8 @@ simdjson_inline simdjson_result simdjson_result= 8; src += 8, len -= 8) { + std::memcpy(&word, src, sizeof(word)); + word ^= BACKSLASHES; + if ((word - ONES) & ~word & HIGHS) { return true; } + } + uint64_t keep; + std::memcpy(&keep, KEEP + 8 - len, sizeof(keep)); + std::memcpy(&word, src, sizeof(word)); + word = (word ^ BACKSLASHES) | ~keep; + return ((word - ONES) & ~word & HIGHS) != 0; +} + +simdjson_warn_unused simdjson_never_inline error_code json_iterator::validate_container() noexcept { + const uint8_t *const json = token.buf; + token_position pos = token.position(); + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // One bit per depth tells whether the container at that depth is an array. Deeper than + // the fixed stack allows, the bits move to the heap. + uint64_t fixed_stack[16]{}; + std::unique_ptr heap_stack; + uint64_t *is_array = fixed_stack; + size_t depth = 0; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VALIDATE_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VALIDATE_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': goto scalar_string; + default: goto scalar; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. Its bit may then + // be at max_depth, which the stack has room for. + if (++depth >= max_depth && (pos == end || json[*pos] != c + 2)) { return DEPTH_ERROR; } + // The bits move once: the next time this depth is reached, the heap holds the current + // bits and the fixed stack holds stale ones. + if (depth == sizeof(fixed_stack) * 8 && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint64_t[max_depth / 64 + 1]()); + if (!heap_stack) { return MEMALLOC; } + std::memcpy(heap_stack.get(), fixed_stack, sizeof(fixed_stack)); + is_array = heap_stack.get(); + } + if (c == '[') { + is_array[depth / 64] |= uint64_t(1) << (depth % 64); + SIMDJSON_VALIDATE_NEXT(); + if (c == ']') { goto container_end; } + goto value; + } + is_array[depth / 64] &= ~(uint64_t(1) << (depth % 64)); + SIMDJSON_VALIDATE_NEXT(); + if (c == '}') { goto container_end; } + goto key; + +key: + if (c != '"') { return TAPE_ERROR; } + // A string is valid once stage 1 has accepted the document, unless it holds an escape. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + SIMDJSON_VALIDATE_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VALIDATE_NEXT(); + goto value; + +scalar_string: + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + if (has_backslash(json + index + 1, *pos - index - 1)) { + uint8_t *dst = _string_buf_loc; + if (!parser->implementation->parse_string(json + index + 1, dst, false)) { return STRING_ERROR; } + } + goto value_end; + +scalar: + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + break; + default: + return TAPE_ERROR; + } + // The scalar is not the last token, so the parsers read inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + switch (c) { + case 't': if (!atomparsing::is_valid_true_atom(json + index)) { return T_ATOM_ERROR; } break; + case 'f': if (!atomparsing::is_valid_false_atom(json + index)) { return F_ATOM_ERROR; } break; + case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (!atomparsing::is_valid_null_atom(json + index) && !atomparsing::is_valid_nan_atom(json + index)) { return N_ATOM_ERROR; } +#else + if (!atomparsing::is_valid_null_atom(json + index)) { return N_ATOM_ERROR; } +#endif + break; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': if (!atomparsing::is_valid_nan_atom(json + index)) { return TAPE_ERROR; } break; + case 'i': case 'I': if (!atomparsing::is_valid_inf_atom(json + index)) { return TAPE_ERROR; } break; +#endif + default: + if (numberparsing::parse_double(json + index).error()) { return NUMBER_ERROR; } + break; + } + +value_end: + SIMDJSON_VALIDATE_NEXT(); + if (c == ',') { + SIMDJSON_VALIDATE_NEXT(); + if (is_array[depth / 64] & (uint64_t(1) << (depth % 64))) { goto value; } + goto key; + } + if (c != (is_array[depth / 64] & (uint64_t(1) << (depth % 64)) ? ']' : '}')) { return TAPE_ERROR; } + +container_end: + if (--depth > 0) { goto value_end; } +#undef SIMDJSON_VALIDATE_NEXT + if (!streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_number(const number &value, const char *raw, V &visitor) { + switch (value.get_number_type()) { + case number_type::signed_integer: return visitor.on_int64(value.get_int64(), raw); + case number_type::unsigned_integer: return visitor.on_uint64(value.get_uint64(), raw); + case number_type::floating_point_number: return visitor.on_double(value.get_double(), raw); + default: return BIGINT_ERROR; + } +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_string(const uint8_t *quote, bool key, V &visitor) { + const uint8_t *const start = quote + 1; + // A string without escapes is passed as it is in the document. + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (const uint8_t *src = start;; src += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(src, scratch); + if (bs_quote.has_quote_first()) { + std::string_view text(reinterpret_cast(start), size_t(src - start) + size_t(bs_quote.quote_index())); + return key ? visitor.on_key(text) : visitor.on_string(text); + } + if (bs_quote.has_backslash()) { break; } + } + uint8_t *const end = parser->implementation->parse_string(start, _string_buf_loc, false); + if (!end) { return STRING_ERROR; } + std::string_view text(reinterpret_cast(_string_buf_loc), size_t(end - _string_buf_loc)); + _string_buf_loc = end; + return key ? visitor.on_key(text) : visitor.on_string(text); +} + +template +simdjson_warn_unused simdjson_inline error_code json_iterator::visit_scalar(const uint8_t *src, V &visitor) { + switch (*src) { + case 't': return atomparsing::is_valid_true_atom(src) ? visitor.on_bool(true) : T_ATOM_ERROR; + case 'f': return atomparsing::is_valid_false_atom(src) ? visitor.on_bool(false) : F_ATOM_ERROR; + case 'n': + if (atomparsing::is_valid_null_atom(src)) { return visitor.on_null(); } +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } +#endif + return N_ATOM_ERROR; + case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + { + number value; + SIMDJSON_TRY(numberparsing::parse_number(src, value)); + return visit_number(value, reinterpret_cast(src), visitor); + } +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(src)) { return visitor.on_double(std::numeric_limits::quiet_NaN(), reinterpret_cast(src)); } + return TAPE_ERROR; + case 'i': case 'I': + if (atomparsing::is_valid_inf_atom(src)) { return visitor.on_double(std::numeric_limits::infinity(), reinterpret_cast(src)); } + return TAPE_ERROR; +#endif + default: + return TAPE_ERROR; + } +} + +template +simdjson_warn_unused error_code json_iterator::visit_container(V &visitor, token_position start, size_t parent_depth) { + const uint8_t *const json = token.buf; + token_position pos = start; + const token_position end = end_position(); + const size_t max_depth = parser->max_depth(); + // For each open container, the number of its elements so far, with the top bit set for an + // array. Deeper than the fixed stack allows, the stack moves to the heap. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + constexpr size_t FIXED_DEPTH = 64; + uint32_t fixed_stack[FIXED_DEPTH]; + std::unique_ptr heap_stack; + uint32_t *stack = fixed_stack; + size_t depth = parent_depth; + uint32_t index; + uint8_t c; + +// Reads the next token into index and c; a document cut short has no more tokens. +#define SIMDJSON_VISIT_NEXT() \ + do { \ + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } \ + index = *pos++; \ + c = json[index]; \ + } while (0) + + SIMDJSON_VISIT_NEXT(); + goto container_start; + +value: + switch (c) { + case '{': case '[': goto container_start; + case '"': + // A string is not the last token, so that its closing quote is inside the document. + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, false, visitor)); + goto value_end; + default: + // The scalar is not the last token, so the parsers read inside the document. + if (simdjson_unlikely(pos == end)) { + switch (c) { + case 't': case 'f': case 'n': case '-': case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': +#if SIMDJSON_ENABLE_NAN_INF + case 'N': case 'i': case 'I': +#endif + return INCOMPLETE_ARRAY_OR_OBJECT; + default: + return TAPE_ERROR; + } + } + SIMDJSON_TRY(visit_scalar(json + index, visitor)); + goto value_end; + } + +container_start: + // As in DOM, an empty container does not count toward the maximal depth. + if (pos != end && json[*pos] == c + 2) { + pos++; + if (c == '[') { + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_TRY(visitor.on_array_end(0)); + } else { + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_TRY(visitor.on_object_end(0)); + } + if (depth == parent_depth) { goto document_end; } + goto value_end; + } + if (++depth >= max_depth) { return DEPTH_ERROR; } + // Copy the fixed stack once. A later container at this depth must keep the + // counts already stored on the heap. + if (depth >= FIXED_DEPTH && !heap_stack) { + heap_stack.reset(new (std::nothrow) uint32_t[max_depth]); + if (!heap_stack) { return MEMALLOC; } + // Only the slots past the parent were written. + if (parent_depth + 1 < FIXED_DEPTH) { + std::memcpy(heap_stack.get() + parent_depth + 1, fixed_stack + parent_depth + 1, (FIXED_DEPTH - parent_depth - 1) * sizeof(fixed_stack[0])); + } + stack = heap_stack.get(); + } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_TRY(visitor.on_array_start()); + SIMDJSON_VISIT_NEXT(); + goto value; + } + SIMDJSON_TRY(visitor.on_object_start()); + SIMDJSON_VISIT_NEXT(); + +key: + if (c != '"') { return TAPE_ERROR; } + if (pos == end) { return INCOMPLETE_ARRAY_OR_OBJECT; } + SIMDJSON_TRY(visit_string(json + index, true, visitor)); + SIMDJSON_VISIT_NEXT(); + if (c != ':') { return TAPE_ERROR; } + SIMDJSON_VISIT_NEXT(); + goto value; + +value_end: + SIMDJSON_VISIT_NEXT(); + if (c == ',') { + stack[depth]++; + SIMDJSON_VISIT_NEXT(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_TRY(visitor.on_object_end(stack[depth])); + } + if (--depth > parent_depth) { goto value_end; } + +document_end: +#undef SIMDJSON_VISIT_NEXT + if (parent_depth == 0 && !streaming() && pos != end) { return TRAILING_CONTENT; } + return SUCCESS; +} + simdjson_inline bool json_iterator::at_root() const noexcept { return position() == root_position(); } @@ -231743,10 +245140,20 @@ simdjson_warn_unused simdjson_inline bool json_iterator::copy_to_buffer(const ui // peek_root_length() stops at the next structural index. Stage 1 omits the // comma or RS (0x1E) that separates stream documents, so that byte and the // whitespace around it remain in the span. RS is not a valid number finisher. + // Outside of a stream, the comma and RS are not separators: some kernels + // keep RS in the scalar token, and dropping it would accept "1\x1e". while (max_len > 0) { const uint8_t last = json[max_len - 1]; + // iterate_allow_incomplete_json() reuses _streaming, so a root scalar + // there is not a document_stream. +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + const bool separator = _streaming && !_allow_incomplete_json && + (last == ',' || last == 0x1E); +#else + const bool separator = _streaming && (last == ',' || last == 0x1E); +#endif if (last != ' ' && last != '\t' && last != '\n' && last != '\r' && - last != ',' && last != 0x1E) { + !separator) { break; } max_len--; @@ -233176,22 +246583,22 @@ simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capa return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - std::unique_ptr new_string_buf(new (std::nothrow) uint8_t[string_capacity]); - if (!new_string_buf) { return MEMALLOC; } + simdjson::internal::allocated_array new_string_buf; + if (!new_string_buf.allocate(string_capacity, _allocator)) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr new_start_positions(new (std::nothrow) token_position[new_max_depth]); if (!new_start_positions) { return MEMALLOC; } #endif - if (implementation) { - error_code err = implementation->allocate(new_capacity, new_max_depth); - if (err) { return err; } - } else { - error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (!implementation) { + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(0, new_max_depth, implementation); if (err) { implementation.reset(); return err; } } + implementation->allocator = _allocator; + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } string_buf = std::move(new_string_buf); #if SIMDJSON_DEVELOPMENT_CHECKS start_positions = std::move(new_start_positions); @@ -233220,9 +246627,42 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iterate(p // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return document::start({ reinterpret_cast(json.data()), this }); } +// Removes from the structural indexes each comma that follows a value and +// precedes a closing bracket, so that the iterator never sees it. The entries +// past the last index (stage 1 keeps up to three there) move with the others. +#if SIMDJSON_ALLOW_TRAILING_COMMAS +simdjson_inline void parser::drop_trailing_commas(const uint8_t *buf) noexcept { + uint32_t *indexes = implementation->structural_indexes.get(); + const uint32_t n = implementation->n_structural_indexes; + uint32_t kept = 0; + uint8_t previous = '['; + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = buf[indexes[i]]; + if (c == ',' && i + 1 < n && previous != '[' && previous != '{' && previous != ',' && previous != ':') { + const uint8_t next = buf[indexes[i + 1]]; + if (next == ']' || next == '}') { + previous = c; + continue; + } + } + indexes[kept++] = indexes[i]; + previous = c; + } + if (kept != n) { + indexes[kept] = indexes[n]; + indexes[kept + 1] = indexes[n + 1]; + indexes[kept + 2] = indexes[n + 2]; + implementation->n_structural_indexes = kept; + } +} +#endif // SIMDJSON_ALLOW_TRAILING_COMMAS + #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_warn_unused simdjson_inline simdjson_result parser::iterate_allow_incomplete_json(padded_string_view json) & noexcept { if (!json.has_sufficient_padding()) { return INSUFFICIENT_PADDING; } @@ -233326,9 +246766,210 @@ simdjson_warn_unused simdjson_inline simdjson_result parser::iter // Run stage 1. SIMDJSON_TRY( implementation->stage1(reinterpret_cast(json.data()), json.length(), stage1_mode::regular) ); +#if SIMDJSON_ALLOW_TRAILING_COMMAS + drop_trailing_commas(reinterpret_cast(json.data())); +#endif return json_iterator(reinterpret_cast(json.data()), this); } +namespace { +struct ignoring_visitor { + simdjson_inline error_code on_object_start() { return SUCCESS; } + simdjson_inline error_code on_object_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_array_start() { return SUCCESS; } + simdjson_inline error_code on_array_end(uint32_t) { return SUCCESS; } + simdjson_inline error_code on_key(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_string(std::string_view) { return SUCCESS; } + simdjson_inline error_code on_int64(int64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_uint64(uint64_t, const char *) { return SUCCESS; } + simdjson_inline error_code on_double(double, const char *) { return SUCCESS; } + simdjson_inline error_code on_bool(bool) { return SUCCESS; } + simdjson_inline error_code on_null() { return SUCCESS; } +}; +} // unnamed namespace + +template +simdjson_warn_unused simdjson_inline error_code parser::visit(padded_string_view json, V &visitor) & { +#if !SIMDJSON_ENABLE_NAN_INF && !SIMDJSON_ALLOW_TRAILING_COMMAS + if (json.length() <= MAX_ONE_PASS_VISIT && json.has_sufficient_padding()) { + if (capacity() < json.length() || !string_buf) { + SIMDJSON_TRY( allocate(json.length(), max_depth()) ); + } + bool visitor_failed = false; + const error_code error = visit_one_pass(reinterpret_cast(json.data()), json.length(), visitor, visitor_failed); + if (error != UNINITIALIZED) { + if (error != TAPE_ERROR || visitor_failed) { return error; } + // The visitor has already seen part of the document: the regular walk only finds the + // error code, and never calls the visitor a second time. + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + ignoring_visitor ignoring; + const error_code regular_error = doc.visit(ignoring); + return regular_error ? regular_error : TAPE_ERROR; + } + } +#endif + document doc; + SIMDJSON_TRY( iterate(json).get(doc) ); + return doc.visit(visitor); +} + +// A single pass over the bytes, for small documents. The root must be an array or an object, and +// the last byte that is not whitespace must be ] or }: before it, runs of whitespace, digits or +// atoms stop without a bound check. Only a closing bracket or a string may reach the end. +template +simdjson_warn_unused simdjson_inline error_code parser::visit_one_pass(const uint8_t *const buf, const size_t len, V &visitor, bool &visitor_failed) { + const auto is_whitespace = [](uint8_t c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t'; }; + if (len == 0 || len > MAX_ONE_PASS_VISIT) { return UNINITIALIZED; } + const uint8_t *p = buf; + const uint8_t *last = buf + len - 1; + while (p < last && is_whitespace(*p)) { p++; } + while (last > p && is_whitespace(*last)) { last--; } + if ((*p != '{' && *p != '[') || (*last != '}' && *last != ']')) { return UNINITIALIZED; } + const uint8_t *const end = last + 1; + uint8_t *dst = string_buf.get(); + bool non_ascii = false; + // For each open container, the number of its elements so far, with the top bit set for an + // array. Each container opens at a distinct byte before the last one, so that the depth stays + // below MAX_ONE_PASS_VISIT. + constexpr uint32_t ARRAY_BIT = uint32_t(1) << 31; + uint32_t stack[MAX_ONE_PASS_VISIT]; + size_t depth = 0; + uint8_t c = *p; + +#define SIMDJSON_ONE_PASS_CALL(EXPR) \ + do { \ + const error_code one_pass_error = (EXPR); \ + if (simdjson_unlikely(one_pass_error != SUCCESS)) { visitor_failed = true; return one_pass_error; } \ + } while (0) +#define SIMDJSON_ONE_PASS_WHITESPACE() while (is_whitespace(*p)) { p++; } +// The string at p, which is left past the closing quote. +#define SIMDJSON_ONE_PASS_STRING(METHOD) \ + do { \ + const uint8_t *const start = ++p; \ + bool escaped = false; \ + for (;; p++) { \ + if (simdjson_unlikely(p >= end)) { return TAPE_ERROR; } \ + if (*p == '"') { break; } \ + if (*p == '\\') { \ + escaped = true; \ + p++; \ + } else if (simdjson_unlikely(*p < 0x20)) { \ + return TAPE_ERROR; \ + } else if (*p >= 0x80) { \ + non_ascii = true; \ + } \ + } \ + std::string_view text(reinterpret_cast(start), size_t(p - start)); \ + p++; \ + if (escaped) { \ + uint8_t *const unescaped_end = implementation->parse_string(start, dst, false); \ + if (unescaped_end == nullptr) { return TAPE_ERROR; } \ + text = std::string_view(reinterpret_cast(dst), size_t(unescaped_end - dst)); \ + dst = unescaped_end; \ + } \ + SIMDJSON_ONE_PASS_CALL(visitor.METHOD(text)); \ + } while (0) + + goto container_start; + +value: + switch (*p) { + case '{': case '[': + c = *p; + goto container_start; + case '"': + SIMDJSON_ONE_PASS_STRING(on_string); + goto value_end; + case 't': + if (!atomparsing::is_valid_true_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(true)); + p += 4; + goto value_end; + case 'f': + if (!atomparsing::is_valid_false_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_bool(false)); + p += 5; + goto value_end; + case 'n': + if (!atomparsing::is_valid_null_atom(p)) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_null()); + p += 4; + goto value_end; + default: { + number value; + if (numberparsing::parse_number(p, value) != SUCCESS) { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(json_iterator::visit_number(value, reinterpret_cast(p), visitor)); + while (jsoncharutils::is_not_structural_or_whitespace(*p)) { p++; } + goto value_end; + } + } + +container_start: + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + // As in DOM, an empty container does not count toward the maximal depth. + if (*p == c + 2) { + p++; + if (c == '[') { + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(0)); + } else { + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(0)); + } + if (depth == 0) { goto document_end; } + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + if (++depth >= max_depth()) { return TAPE_ERROR; } + stack[depth] = 1; + if (c == '[') { + stack[depth] |= ARRAY_BIT; + SIMDJSON_ONE_PASS_CALL(visitor.on_array_start()); + goto value; + } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_start()); + +key: + if (*p != '"') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_STRING(on_key); + SIMDJSON_ONE_PASS_WHITESPACE(); + if (*p != ':') { return TAPE_ERROR; } + p++; + SIMDJSON_ONE_PASS_WHITESPACE(); + goto value; + +value_end: + SIMDJSON_ONE_PASS_WHITESPACE(); + c = *p++; + if (c == ',') { + stack[depth]++; + SIMDJSON_ONE_PASS_WHITESPACE(); + if (stack[depth] & ARRAY_BIT) { goto value; } + goto key; + } + if (stack[depth] & ARRAY_BIT) { + if (c != ']') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_array_end(stack[depth] & ~ARRAY_BIT)); + } else { + if (c != '}') { return TAPE_ERROR; } + SIMDJSON_ONE_PASS_CALL(visitor.on_object_end(stack[depth])); + } + if (--depth > 0) { + if (p == end) { return TAPE_ERROR; } + goto value_end; + } + +document_end: +#undef SIMDJSON_ONE_PASS_CALL +#undef SIMDJSON_ONE_PASS_WHITESPACE +#undef SIMDJSON_ONE_PASS_STRING + if (p != end) { return TAPE_ERROR; } + if (non_ascii && !simdjson::validate_utf8(reinterpret_cast(buf), len)) { return TAPE_ERROR; } + return SUCCESS; +} + inline simdjson_result parser::iterate_many(const uint8_t *buf, size_t len, size_t batch_size) noexcept { if(batch_size < MINIMAL_BATCH_SIZE) { batch_size = MINIMAL_BATCH_SIZE; } if((len >= 3) && (std::memcmp(buf, "\xEF\xBB\xBF", 3) == 0)) { @@ -233446,6 +247087,13 @@ simdjson_pure simdjson_inline size_t parser::max_depth() const noexcept { return _max_depth; } +simdjson_inline void parser::set_allocator(const buffer_allocator *allocator) noexcept { + _allocator = allocator; +} +simdjson_pure simdjson_inline const buffer_allocator *parser::get_allocator() const noexcept { + return _allocator; +} + simdjson_inline void parser::set_max_capacity(size_t max_capacity) noexcept { if(max_capacity > dom::MINIMAL_DOCUMENT_CAPACITY) { _max_capacity = max_capacity; @@ -233965,13 +247613,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_objec _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing } at end"); } - // If the last character is } *and* the first gibberish character is also '}' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is } *and* the first gibberish character is '}', ']' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == '}') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed object. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -234375,13 +248025,15 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_array _json_iter->abandon(); return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "missing ] at end"); } - // If the last character is ] *and* the first gibberish character is also ']' - // then on-demand could accidentally go over. So we need additional checks. + // If the last character is ] *and* the first gibberish character is ']', '}' or ',' + // then on-demand could accidentally go over: an unclosed inner container reads it + // as its end or as a separator. So we need additional checks. // https://github.com/simdjson/simdjson/issues/1834 // Checking that the document is balanced requires a full scan which is potentially // expensive, but it only happens in edge cases where the first padding character is - // a closing bracket. - if ((*_json_iter->peek(_json_iter->end_position()) == ']') && (!_json_iter->balanced())) { + // a closing bracket or a comma. + const uint8_t after_end = *_json_iter->peek(_json_iter->end_position()); + if ((after_end == '}' || after_end == ']' || after_end == ',') && (!_json_iter->balanced())) { _json_iter->abandon(); // The exact error would require more work. It will typically be an unclosed array. return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "the document is unbalanced"); @@ -234551,7 +248203,7 @@ simdjson_inline simdjson_result value_iterator::get_root_n // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -234575,7 +248227,7 @@ simdjson_inline simdjson_result value_iterator::get_root_number(bool che // number: -0.e-308. // NOTE: the current approach doesn't work for very big integer numbers containing more than 1074 digits. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -234657,7 +248309,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::g simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+1+1]; // -<19 digits> is the longest possible integer tmpbuf[20+1] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+1)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 20 characters"); @@ -234674,7 +248326,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::ge simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_root_int64_in_string(bool check_trailing) noexcept { auto max_len = peek_root_length(); auto json = peek_root_scalar("int64"); - uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer + simdjson_indeterminate uint8_t tmpbuf[20+2+1]; // "-<19 digits>" is the longest possible integer tmpbuf[20+2] = '\0'; // make sure that buffer is always null terminated. if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 20+2)) { logger::log_error(*_json_iter, start_position(), depth(), "Root number more than 22 characters"); @@ -234695,7 +248347,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -234717,7 +248369,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get // 1074 is the maximum number of significant fractional digits. Add 8 more digits for the biggest // number: -0.e-308. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -234739,7 +248391,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ // digits that matter is smaller for binary32, but the JSON document may still // spell out a long number that we must parse (and round) faithfully. // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -234758,7 +248410,7 @@ simdjson_warn_unused simdjson_inline simdjson_result value_iterator::get_ auto max_len = peek_root_length(); auto json = peek_root_scalar("float"); // +SIMDJSON_PADDING: the digit scan reads up to 7 bytes past the terminator. - uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. + simdjson_indeterminate uint8_t tmpbuf[1074+8+1+1+SIMDJSON_PADDING]; // +1 for null termination. // Null terminate, and zero the padding as allocate_padded_buffer does. std::memset(tmpbuf+1074+8+1, 0, 1+SIMDJSON_PADDING); if (!_json_iter->copy_to_buffer(json, max_len, tmpbuf, 1074+8+1)) { @@ -235096,6 +248748,9 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '"': return json_type::string; case 'n': +#if SIMDJSON_ENABLE_NAN_INF + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } +#endif return json_type::null; case 't': case 'f': return json_type::boolean; @@ -235103,6 +248758,14 @@ simdjson_inline simdjson_result value_iterator::type() const noexcept case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return json_type::number; +#if SIMDJSON_ENABLE_NAN_INF + case 'N': + if (atomparsing::is_valid_nan_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; + case 'I': case 'i': + if (atomparsing::is_valid_inf_atom(peek_start(), peek_start_length())) { return json_type::number; } + return json_type::unknown; +#endif default: return json_type::unknown; } @@ -236168,11 +249831,23 @@ struct auto_parser { parser_type m_parser; ondemand::document m_doc; error_code m_error{SUCCESS}; + // Original buffer, when this auto_parser was built from a string. Used to + // direct-parse atoms and arrays of atoms without a structural index. + // Lifetime is the caller's buffer, same rule as ondemand::iterate. + const uint8_t *m_direct_buf{nullptr}; + size_t m_direct_len{0}; + size_t m_direct_cap{0}; + // True when m_doc was produced by iterate (or supplied by the caller). + // String constructors leave this false so result() can direct-parse first. + bool m_doc_ready{false}; template static constexpr bool is_nothrow_gettable = requires(ondemand::document doc) { { doc.get() } noexcept; }; + template + static constexpr bool views_document = std::is_same_v || std::is_same_v + || std::is_same_v || std::is_same_v; public: explicit auto_parser(parser_type &&parser, ondemand::document &&doc) noexcept requires(!std::is_pointer_v); explicit auto_parser(parser_type &&parser, padded_string_view const str) noexcept requires(!std::is_pointer_v); @@ -236188,24 +249863,42 @@ struct auto_parser { auto_parser &operator=(auto_parser &&) noexcept = delete; simdjson_warn_unused std::remove_pointer_t &parser() noexcept; + // An array, an object, a value or a document_reference points into the document + // held by this auto_parser, so it cannot be taken from a temporary: + // simdjson::from(json).array() would dangle once the full-expression ends. template - simdjson_warn_unused simdjson_inline simdjson_result result() noexcept(is_nothrow_gettable); + simdjson_warn_unused simdjson_inline simdjson_result result() & noexcept(is_nothrow_gettable); template - simdjson_warn_unused simdjson_inline error_code get(T &value) && noexcept(is_nothrow_gettable); - + simdjson_warn_unused simdjson_inline simdjson_result result() && noexcept(is_nothrow_gettable) requires(!views_document); + template + simdjson_result result() && requires(views_document) = delete; + template + simdjson_warn_unused simdjson_inline error_code get(T &value) && noexcept(is_nothrow_gettable) requires(!views_document); + template + error_code get(T &value) && requires(views_document) = delete; - simdjson_warn_unused simdjson_inline simdjson_result array() noexcept; - simdjson_warn_unused simdjson_inline simdjson_result object() noexcept; + simdjson_warn_unused simdjson_inline simdjson_result array() & noexcept; + simdjson_warn_unused simdjson_inline simdjson_result object() & noexcept; + simdjson_result array() && = delete; + simdjson_result object() && = delete; simdjson_warn_unused simdjson_inline simdjson_result number() noexcept; #if SIMDJSON_EXCEPTIONS template - simdjson_warn_unused simdjson_inline explicit(false) operator T() noexcept(false); + simdjson_warn_unused simdjson_inline explicit(false) operator T() & noexcept(false); + template + simdjson_warn_unused simdjson_inline explicit(false) operator T() && noexcept(false) requires(!views_document); + template + explicit(false) operator T() && requires(views_document) = delete; #endif // SIMDJSON_EXCEPTIONS template - simdjson_warn_unused simdjson_inline std::optional optional() noexcept(is_nothrow_gettable); + simdjson_warn_unused simdjson_inline std::optional optional() & noexcept(is_nothrow_gettable); + template + simdjson_warn_unused simdjson_inline std::optional optional() && noexcept(is_nothrow_gettable) requires(!views_document); + template + std::optional optional() && requires(views_document) = delete; }; @@ -236272,28 +249965,588 @@ static constexpr convert::internal::to_adaptor<> from{}; /* skipped duplicate #include "simdjson/convert.h" */ #if SIMDJSON_SUPPORTS_CONCEPTS +/* including simdjson/internal/direct_parse.h: #include "simdjson/internal/direct_parse.h" */ +/* begin file simdjson/internal/direct_parse.h */ +#ifndef SIMDJSON_INTERNAL_DIRECT_PARSE_H +#define SIMDJSON_INTERNAL_DIRECT_PARSE_H + +// Single-pass parsers for JSON atoms and arrays of atoms. They do not build a +// structural index. Except for the double array, they read only buf[0, len) +// (no padding required). Strings are validated as UTF-8 one at a time; a high +// byte outside a string makes them return UNINITIALIZED so the caller can fall +// back to the full parser. +// +// Not part of the public API. + +/* skipped duplicate #include "simdjson/base.h" */ +/* skipped duplicate #include "simdjson/builtin.h" */ +/* skipped duplicate #include "simdjson/error.h" */ +/* skipped duplicate #include "simdjson/implementation.h" */ +/* skipped duplicate #include "simdjson/internal/json_escape.h" */ +/* skipped duplicate #include "simdjson/internal/numberparsing_tables.h" */ + +#include +#include +#include +#include +#include +#include + +namespace simdjson { +namespace internal { +namespace direct { + +simdjson_inline bool is_ws(uint8_t c) noexcept { + return c == ' ' || c == '\t' || c == '\n' || c == '\r'; +} + +// Skip ASCII whitespace. Returns false if a non-ASCII byte is seen. +simdjson_inline bool skip_ws(const uint8_t *&p, const uint8_t *end) noexcept { + while (p < end) { + if (*p >= 0x80) { return false; } + if (!is_ws(*p)) { return true; } + p++; + } + return true; +} + +// Parse a JSON int64 at p. On success p points at the finisher (or end). +// Returns UNINITIALIZED if this is not an int64 token (float, too big, +// non-ASCII); the caller should not treat that as a hard document error +// unless it has already committed to this token being an integer. +simdjson_inline error_code parse_int64_token(const uint8_t *&p, const uint8_t *end, int64_t &out) noexcept { + if (p >= end || *p >= 0x80) { return UNINITIALIZED; } + const bool negative = (*p == '-'); + if (negative) { + p++; + if (p >= end) { return UNINITIALIZED; } + } + if (*p < '0' || *p > '9') { return UNINITIALIZED; } + uint64_t i = 0; + const uint8_t *digits = p; + if (*p == '0') { + p++; + } else { + while (p < end && *p >= '0' && *p <= '9') { + if (size_t(p - digits) >= 19) { + // Too many digits for int64. Consume the rest of the digit run so the + // caller can see what follows, but report not-an-int64. + while (p < end && *p >= '0' && *p <= '9') { p++; } + return UNINITIALIZED; + } + i = i * 10 + uint64_t(*p - '0'); + p++; + } + } + const size_t digit_count = size_t(p - digits); + if (digit_count == 0) { return UNINITIALIZED; } + if (*digits == '0' && digit_count > 1) { return UNINITIALIZED; } + if (p < end && *p >= 0x80) { return UNINITIALIZED; } + if (p < end && (*p == '.' || *p == 'e' || *p == 'E')) { return UNINITIALIZED; } + if (i > uint64_t(INT64_MAX) + uint64_t(negative)) { return UNINITIALIZED; } + out = negative ? int64_t(~i + 1) : int64_t(i); + return SUCCESS; +} + +simdjson_inline error_code parse_uint64_token(const uint8_t *&p, const uint8_t *end, uint64_t &out) noexcept { + // On Demand rejects any sign, including -0. + if (p >= end || *p < '0' || *p > '9') { return UNINITIALIZED; } + uint64_t i = 0; + const uint8_t *digits = p; + if (*p == '0') { + p++; + } else { + while (p < end && *p >= '0' && *p <= '9') { + if (size_t(p - digits) >= 20) { + while (p < end && *p >= '0' && *p <= '9') { p++; } + return UNINITIALIZED; + } + i = i * 10 + uint64_t(*p - '0'); + p++; + } + } + const size_t digit_count = size_t(p - digits); + if (*digits == '0' && digit_count > 1) { return UNINITIALIZED; } + if (p < end && *p >= 0x80) { return UNINITIALIZED; } + if (p < end && (*p == '.' || *p == 'e' || *p == 'E')) { return UNINITIALIZED; } + // A 20-digit value is in range only if it starts with 1 and did not wrap. + if (digit_count == 20 && (*digits != '1' || i <= uint64_t(INT64_MAX))) { return UNINITIALIZED; } + out = i; + return SUCCESS; +} + +simdjson_inline error_code parse_bool_token(const uint8_t *&p, const uint8_t *end, bool &out) noexcept { + if (p >= end || *p >= 0x80) { return UNINITIALIZED; } + if (end - p >= 4 && p[0] == 't' && p[1] == 'r' && p[2] == 'u' && p[3] == 'e') { + p += 4; + out = true; + return SUCCESS; + } + if (end - p >= 5 && p[0] == 'f' && p[1] == 'a' && p[2] == 'l' && p[3] == 's' && p[4] == 'e') { + p += 5; + out = false; + return SUCCESS; + } + return UNINITIALIZED; +} + +simdjson_inline error_code parse_null_token(const uint8_t *&p, const uint8_t *end) noexcept { + if (end - p >= 4 && p[0] == 'n' && p[1] == 'u' && p[2] == 'l' && p[3] == 'l') { + p += 4; + return SUCCESS; + } + return UNINITIALIZED; +} + +// After a value, require only whitespace through end. +simdjson_inline error_code finish_ws_only(const uint8_t *p, const uint8_t *end) noexcept { + if (!skip_ws(p, end)) { return UNINITIALIZED; } + // Trailing junk: let the full parser report the canonical error. + if (p != end) { return UNINITIALIZED; } + return SUCCESS; +} + +template +simdjson_inline error_code parse_document(const uint8_t *buf, size_t len, T &out); + +template <> +simdjson_inline error_code parse_document(const uint8_t *buf, size_t len, int64_t &out) { + const uint8_t *p = buf; + const uint8_t *end = buf + len; + if (!skip_ws(p, end)) { return UNINITIALIZED; } + if (p == end) { return EMPTY; } + error_code err = parse_int64_token(p, end, out); + if (err != SUCCESS) { return err; } + return finish_ws_only(p, end); +} + +template <> +simdjson_inline error_code parse_document(const uint8_t *buf, size_t len, uint64_t &out) { + const uint8_t *p = buf; + const uint8_t *end = buf + len; + if (!skip_ws(p, end)) { return UNINITIALIZED; } + if (p == end) { return EMPTY; } + error_code err = parse_uint64_token(p, end, out); + if (err != SUCCESS) { return err; } + return finish_ws_only(p, end); +} + +template <> +simdjson_inline error_code parse_document(const uint8_t *buf, size_t len, bool &out) { + const uint8_t *p = buf; + const uint8_t *end = buf + len; + if (!skip_ws(p, end)) { return UNINITIALIZED; } + if (p == end) { return EMPTY; } + error_code err = parse_bool_token(p, end, out); + if (err != SUCCESS) { return err; } + return finish_ws_only(p, end); +} + +// The first byte at or after p that is '"', '\\', a control character or +// (when stop_on_high is set) non-ASCII, or end. +template +simdjson_inline const uint8_t *find_string_stop(const uint8_t *p, const uint8_t *end) noexcept { +#if SIMDJSON_EXPERIMENTAL_HAS_SSE2 + // Sixteen bytes at a time with SSE2, which every x64 processor has. + const __m128i quote_v = _mm_set1_epi8('"'); + const __m128i backslash_v = _mm_set1_epi8('\\'); + const __m128i control_max = _mm_set1_epi8(0x1f); + while (end - p >= 16) { + const __m128i v = _mm_loadu_si128(reinterpret_cast(p)); + const __m128i control = _mm_cmpeq_epi8(_mm_max_epu8(v, control_max), control_max); + const __m128i stops = _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(v, quote_v), _mm_cmpeq_epi8(v, backslash_v)), control); + uint32_t bits = uint32_t(_mm_movemask_epi8(stops)); + if (stop_on_high) { bits |= uint32_t(_mm_movemask_epi8(v)); } + if (bits != 0) { return p + trailing_zeroes(bits); } + p += 16; + } +#elif SIMDJSON_EXPERIMENTAL_HAS_NEON + // Sixteen bytes at a time with NEON. The narrowing shift keeps four bits + // per byte, so the lowest set bit divided by four is the byte index. + const uint8x16_t quote_v = vdupq_n_u8('"'); + const uint8x16_t backslash_v = vdupq_n_u8('\\'); + const uint8x16_t space = vdupq_n_u8(0x20); + const uint8x16_t high = vdupq_n_u8(0x80); + while (end - p >= 16) { + const uint8x16_t v = vld1q_u8(p); + uint8x16_t stops = vorrq_u8(vorrq_u8(vceqq_u8(v, quote_v), vceqq_u8(v, backslash_v)), vcltq_u8(v, space)); + if (stop_on_high) { stops = vorrq_u8(stops, vcgeq_u8(v, high)); } + const uint64_t bits = vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vreinterpretq_u16_u8(stops), 4)), 0); + if (bits != 0) { return p + (trailing_zeroes(bits) >> 2); } + p += 16; + } +#endif +#if !SIMDJSON_IS_BIG_ENDIAN + // Eight bytes at a time. A byte's high bit is set in hits when it stops the + // scan. A borrow can only set bits above a real hit, so the lowest set bit + // is exact. + constexpr uint64_t ones = 0x0101010101010101ull; + constexpr uint64_t highs = 0x8080808080808080ull; + while (end - p >= 8) { + uint64_t w; + std::memcpy(&w, p, 8); + const uint64_t quote = w ^ (ones * '"'); + const uint64_t backslash = w ^ (ones * '\\'); + const uint64_t hits = (((quote - ones) & ~quote) | ((backslash - ones) & ~backslash) | + ((w - ones * 0x20) & ~w) | (stop_on_high ? w : 0)) & highs; + if (hits != 0) { return p + (trailing_zeroes(hits) >> 3); } + p += 8; + } +#endif + while (p < end && *p != '"' && *p != '\\' && *p >= 0x20 && (!stop_on_high || *p < 0x80)) { p++; } + return p; +} + +// Short strings are copied with fixed-size moves: a memcpy of the exact length +// is an out-of-line call whose length branches mispredict. +simdjson_inline void copy_short(char *dst, const uint8_t *src, size_t n) noexcept { + if (n >= 16) { + if (n <= 32) { + std::memcpy(dst, src, 16); + std::memcpy(dst + n - 16, src + n - 16, 16); + } else if (n <= 64) { + std::memcpy(dst, src, 32); + std::memcpy(dst + n - 32, src + n - 32, 32); + } else { + std::memcpy(dst, src, n); + } + } else if (n >= 8) { + std::memcpy(dst, src, 8); + std::memcpy(dst + n - 8, src + n - 8, 8); + } else if (n >= 4) { + std::memcpy(dst, src, 4); + std::memcpy(dst + n - 4, src + n - 4, 4); + } else if (n > 0) { + dst[0] = char(src[0]); + dst[n >> 1] = char(src[n >> 1]); + dst[n - 1] = char(src[n - 1]); + } +} + +simdjson_inline void assign_plain_string(std::string &out, const uint8_t *src, size_t n) { +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE + out.resize_and_overwrite(n, [src, n](char *dst, size_t) noexcept { + copy_short(dst, src, n); + return n; + }); +#else + // Not assign(): extra call sites of std::string::assign make GCC stop + // inlining it in On-Demand string code compiled in the same file. The + // output is always a fresh string, so there is no buffer to reuse. + out = std::string(reinterpret_cast(src), n); +#endif +} + +// String body at s (after the opening quote) that holds an escape or a +// non-ASCII byte. Unescapes like stage 2 with allow_replacement off; any +// escape it would reject, or a control character, returns UNINITIALIZED. +simdjson_never_inline error_code parse_escaped_string_body(const uint8_t *&p, const uint8_t *s, const uint8_t *stop, const uint8_t *end, std::string &out) { + // Find the closing quote, resuming at stop, the first byte that the caller's + // ASCII scan rejected. A backslash always covers the next byte. The scan + // stops on non-ASCII bytes until it meets the first one, so that an ASCII + // string skips UTF-8 validation. + const uint8_t *close = stop; + bool has_escape = false; + bool has_high = false; + for (;;) { + close = has_high ? find_string_stop(close, end) : find_string_stop(close, end); + if (close == end || *close < 0x20) { return UNINITIALIZED; } + if (*close == '"') { break; } + if (*close == '\\') { + if (end - close < 2) { return UNINITIALIZED; } + has_escape = true; + close += 2; + } else { + has_high = true; + close++; + } + } + const size_t n = size_t(close - s); + if (has_high && !simdjson::validate_utf8(reinterpret_cast(s), n)) { return UNINITIALIZED; } + if (!has_escape) { + assign_plain_string(out, s, n); + p = close + 1; + return SUCCESS; + } + // Every escape is at least as long as the bytes it stands for. + out.resize(n); + uint8_t *const dst_start = reinterpret_cast(&out[0]); + uint8_t *dst = dst_start; + const uint8_t *src = s; + while (src < close) { + // Between src and close, the only stop is a backslash: quotes are escaped + // and control characters were rejected by the scan above. + const uint8_t *backslash = find_string_stop(src, close); + std::memcpy(dst, src, size_t(backslash - src)); + dst += backslash - src; + src = backslash; + if (src == close) { break; } + uint8_t c = src[1]; + if (c == 'u') { + namespace jsoncharutils = simdjson::builtin::jsoncharutils; + if (close - src < 6) { return UNINITIALIZED; } + uint32_t code_point = jsoncharutils::hex_to_u32_nocheck(src + 2); + src += 6; + if (code_point >= 0xd800 && code_point < 0xdc00) { + if (close - src < 6 || src[0] != '\\' || src[1] != 'u') { return UNINITIALIZED; } + const uint32_t low_bit = jsoncharutils::hex_to_u32_nocheck(src + 2) - 0xdc00; + if (low_bit >> 10) { return UNINITIALIZED; } + code_point = (((code_point - 0xd800) << 10) | low_bit) + 0x10000; + src += 6; + } else if (code_point >= 0xdc00 && code_point <= 0xdfff) { + return UNINITIALIZED; + } + const size_t written = jsoncharutils::codepoint_to_utf8(code_point, dst); + if (written == 0) { return UNINITIALIZED; } + dst += written; + continue; + } + switch (c) { + case '"': case '\\': case '/': break; + case 'b': c = '\b'; break; + case 'f': c = '\f'; break; + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + default: return UNINITIALIZED; + } + *dst++ = c; + src += 2; + } + out.resize(size_t(dst - dst_start)); + p = close + 1; + return SUCCESS; +} + +// JSON string token. Plain ASCII strings take the inline path; escapes and +// non-ASCII bytes go through parse_escaped_string_body. +simdjson_inline error_code parse_string_token(const uint8_t *&p, const uint8_t *end, std::string &out) { + if (p >= end || *p != '"') { return UNINITIALIZED; } + const uint8_t *start = p + 1; + const uint8_t *stop = find_string_stop(start, end); + if (simdjson_likely(stop < end && *stop == '"')) { + assign_plain_string(out, start, size_t(stop - start)); + p = stop + 1; + return SUCCESS; + } + return parse_escaped_string_body(p, start, stop, end, out); +} + +// Appends the JSON string token at p to out. A plain ASCII string is +// constructed in place. +simdjson_inline error_code append_string_token(const uint8_t *&p, const uint8_t *end, std::vector &out) { + if (p >= end || *p != '"') { return UNINITIALIZED; } + const uint8_t *start = p + 1; + const uint8_t *stop = find_string_stop(start, end); + if (simdjson_likely(stop < end && *stop == '"')) { + out.emplace_back(reinterpret_cast(start), size_t(stop - start)); + p = stop + 1; + return SUCCESS; + } + out.emplace_back(); + return parse_escaped_string_body(p, start, stop, end, out.back()); +} + +// Containers are sized from the first element, which can underestimate the +// width of the others by a lot (["", ""]). The reservation is +// capped at four times the input size and trimmed when it is mostly unused. +template +simdjson_inline void reserve_from_first(V &out, size_t rest, size_t stride) { + const size_t estimate = rest / stride + 2; + const size_t limit = 4 * rest / sizeof(typename V::value_type) + 2; + out.reserve(estimate < limit ? estimate : limit); +} + +template +simdjson_inline void trim_reservation(V &out) { + if (out.capacity() / 2 > out.size() + 16) { out.shrink_to_fit(); } +} + +template <> +simdjson_inline error_code parse_document(const uint8_t *buf, size_t len, std::string &out) { + const uint8_t *p = buf; + const uint8_t *end = buf + len; + if (!skip_ws(p, end)) { return UNINITIALIZED; } + if (p == end) { return EMPTY; } + error_code err = parse_string_token(p, end, out); + if (err != SUCCESS) { return err; } + return finish_ws_only(p, end); +} + +// Array of strings. Same fallback rules as parse_string_token. +template <> +simdjson_inline error_code parse_document>(const uint8_t *buf, size_t len, std::vector &out) { + const uint8_t *p = buf; + const uint8_t *end = buf + len; + if (!skip_ws(p, end)) { return UNINITIALIZED; } + if (p == end) { return EMPTY; } + if (*p != '[') { return UNINITIALIZED; } + p++; + if (!skip_ws(p, end)) { return UNINITIALIZED; } + out.clear(); + if (p < end && *p == ']') { + p++; + return finish_ws_only(p, end); + } + { + // Size the buffer from the first element; later strings are built in place. + const uint8_t *tok = p; + std::string first; + if (parse_string_token(p, end, first) != SUCCESS) { return UNINITIALIZED; } + reserve_from_first(out, size_t(end - tok), size_t(p - tok) + 1); // string plus comma + out.push_back(std::move(first)); + } + for (;;) { + if (!skip_ws(p, end) || p >= end) { out.clear(); return UNINITIALIZED; } + if (*p == ']') { + p++; + if (finish_ws_only(p, end) != SUCCESS) { out.clear(); return UNINITIALIZED; } + trim_reservation(out); + return SUCCESS; + } + if (*p != ',') { out.clear(); return UNINITIALIZED; } + p++; + if (!skip_ws(p, end)) { out.clear(); return UNINITIALIZED; } + if (append_string_token(p, end, out) != SUCCESS) { out.clear(); return UNINITIALIZED; } + } +} + +// A JSON number at p as a double, with the digit loops and rounding of the On +// Demand number parser. Those read ahead (eight bytes at a time) and stop at +// the first byte that cannot continue a number, so the caller must guarantee +// such a byte before the buffer's padding runs out. Anything that is not a +// finite JSON number returns UNINITIALIZED and leaves p alone. +simdjson_inline error_code parse_double_padded(const uint8_t *&p, double &out) noexcept { + namespace numberparsing = simdjson::builtin::numberparsing; + const uint8_t *const start = p; + const bool negative = (*start == '-'); + const uint8_t *const digits = start + uint8_t(negative); + const uint8_t *q = digits; + uint64_t i = 0; + bool leading_zero; + numberparsing::parse_float_integer_digits(q, i, leading_zero); + if (q == digits || (leading_zero && q != digits + 1)) { return UNINITIALIZED; } + int64_t exponent = 0; + bool overflow; + if (*q == '.') { + q++; + const uint8_t *const first_fraction = q; + numberparsing::parse_fraction_digits(q, i); + if (q == first_fraction) { return UNINITIALIZED; } + exponent = -(q - first_fraction); + overflow = q - digits - 1 > 19; + if (simdjson_unlikely(overflow && leading_zero)) { + // 0.000ddd: the zeros after the point do not count. + const uint8_t *significant = digits + 2; + while (*significant == '0') { significant++; } + overflow = q - significant > 19; + } + } else { + overflow = q - digits > 19; + } + if (*q == 'e' || *q == 'E') { + q++; + const bool exp_negative = (*q == '-'); + q += exp_negative || *q == '+'; + const uint8_t *const first_exp = q; + uint64_t exp = 0; + while (numberparsing::parse_digit(*q, exp)) { q++; } + if (q == first_exp) { return UNINITIALIZED; } + overflow = overflow || q - first_exp > 19; + exponent += exp_negative ? 0 - exp : exp; + } + overflow = overflow || exponent < simdjson::internal::smallest_power || + exponent > simdjson::internal::largest_power; + double d = 0; + if (simdjson_unlikely(overflow || !numberparsing::compute_float_64(exponent, i, negative, d))) { + d = simdjson::internal::from_chars(reinterpret_cast(start), + reinterpret_cast(q)); + if (!(d >= std::numeric_limits::lowest() && d <= (std::numeric_limits::max)())) { + return UNINITIALIZED; + } + } + out = d; + p = q; + return SUCCESS; +} + +// Array of doubles. Needs SIMDJSON_PADDING readable bytes after len: numbers +// are read with parse_double_padded, and requiring the last non-space byte to +// be the closing bracket bounds every number scan. +simdjson_inline error_code parse_padded_document(const uint8_t *buf, size_t len, std::vector &out) { + const uint8_t *p = buf; + const uint8_t *end = buf + len; + if (!skip_ws(p, end)) { return UNINITIALIZED; } + if (p == end) { return EMPTY; } + if (*p != '[') { return UNINITIALIZED; } + const uint8_t *last = end; + while (is_ws(last[-1])) { last--; } + if (last - 1 == p || last[-1] != ']') { return UNINITIALIZED; } + p++; + if (!skip_ws(p, end)) { return UNINITIALIZED; } + out.clear(); + if (*p == ']') { + p++; + return finish_ws_only(p, end); + } + bool reserved = false; + // Every number and separator ends at or before the closing bracket, so + // *p stays in bounds without checking end. + for (;;) { + const uint8_t *tok = p; + double v; + if (parse_double_padded(p, v) != SUCCESS) { out.clear(); return UNINITIALIZED; } + if (!reserved) { + reserve_from_first(out, size_t(end - tok), size_t(p - tok) + 1); + reserved = true; + } + out.push_back(v); + if (*p != ',') { + if (!skip_ws(p, end)) { out.clear(); return UNINITIALIZED; } + if (*p == ']') { + p++; + if (finish_ws_only(p, end) != SUCCESS) { out.clear(); return UNINITIALIZED; } + trim_reservation(out); + return SUCCESS; + } + if (*p != ',') { out.clear(); return UNINITIALIZED; } + } + p++; + if (is_ws(*p) && !skip_ws(p, end)) { out.clear(); return UNINITIALIZED; } + } +} + +} // namespace direct +} // namespace internal +} // namespace simdjson + +#endif // SIMDJSON_INTERNAL_DIRECT_PARSE_H +/* end file simdjson/internal/direct_parse.h */ namespace simdjson { namespace convert { namespace internal { // auto_parser method definitions template inline auto_parser::auto_parser(parser_type &&parser, ondemand::document &&doc) noexcept requires(!std::is_pointer_v) - : m_parser{std::move(parser)}, m_doc{std::move(doc)} {} + : m_parser{std::move(parser)}, m_doc{std::move(doc)}, m_doc_ready{true} {} template inline auto_parser::auto_parser(parser_type &&parser, padded_string_view const str) noexcept requires(!std::is_pointer_v) - : m_parser{std::move(parser)}, m_doc{}, m_error{SUCCESS} { - m_error = m_parser.iterate(str).get(m_doc); + : m_parser{std::move(parser)}, m_doc{}, m_error{SUCCESS}, + m_direct_buf{reinterpret_cast(str.data())}, m_direct_len{str.size()}, + m_direct_cap{str.capacity()}, m_doc_ready{false} { + // iterate is deferred so atoms and arrays of atoms can be direct-parsed. } template inline auto_parser::auto_parser(std::remove_pointer_t &parser, ondemand::document &&doc) noexcept requires(std::is_pointer_v) - : m_parser{&parser}, m_doc{std::move(doc)} {} + : m_parser{&parser}, m_doc{std::move(doc)}, m_doc_ready{true} {} template inline auto_parser::auto_parser(std::remove_pointer_t &parser, padded_string_view const str) noexcept requires(std::is_pointer_v) - : m_parser{&parser}, m_doc{}, m_error{SUCCESS} { - m_error = m_parser->iterate(str).get(m_doc); + : m_parser{&parser}, m_doc{}, m_error{SUCCESS}, + m_direct_buf{reinterpret_cast(str.data())}, m_direct_len{str.size()}, + m_direct_cap{str.capacity()}, m_doc_ready{false} { } template @@ -236316,26 +250569,77 @@ inline std::remove_pointer_t &auto_parser::parser() no template template -inline simdjson_result auto_parser::result() noexcept(is_nothrow_gettable) { +inline simdjson_result auto_parser::result() & noexcept(is_nothrow_gettable) { if (m_error != SUCCESS) { return m_error; } + // Direct single-pass parse for atoms and flat arrays. UNINITIALIZED means + // "not that shape"; fall back to the full ondemand parser. + if constexpr (std::is_same_v || std::is_same_v || + std::is_same_v || + std::is_same_v || std::is_same_v>) { + if (m_direct_buf != nullptr) { + T direct_value{}; + error_code direct_error = simdjson::internal::direct::parse_document( + m_direct_buf, m_direct_len, direct_value); + if (direct_error == SUCCESS) { + return direct_value; + } + if (direct_error != UNINITIALIZED) { + return direct_error; + } + } + } else if constexpr (std::is_same_v>) { + // The number parser reads ahead, so this needs the padding On Demand needs. + if (m_direct_buf != nullptr && m_direct_cap >= m_direct_len + SIMDJSON_PADDING) { + T direct_value{}; + error_code direct_error = simdjson::internal::direct::parse_padded_document( + m_direct_buf, m_direct_len, direct_value); + if (direct_error == SUCCESS) { + return direct_value; + } + if (direct_error != UNINITIALIZED) { + return direct_error; + } + } + } + if (!m_doc_ready) { + if (m_direct_buf == nullptr) { + return UNINITIALIZED; + } + padded_string_view view(reinterpret_cast(m_direct_buf), m_direct_len, m_direct_cap); + if constexpr (std::is_pointer_v) { + m_error = m_parser->iterate(view).get(m_doc); + } else { + m_error = m_parser.iterate(view).get(m_doc); + } + m_doc_ready = true; + if (m_error != SUCCESS) { + return m_error; + } + } return m_doc.get(); } template template -simdjson_warn_unused simdjson_inline error_code auto_parser::get(T &value) && noexcept(is_nothrow_gettable) { +inline simdjson_result auto_parser::result() && noexcept(is_nothrow_gettable) requires(!views_document) { + return result(); +} + +template +template +simdjson_warn_unused simdjson_inline error_code auto_parser::get(T &value) && noexcept(is_nothrow_gettable) requires(!views_document) { return result().get(value); } template -inline simdjson_result auto_parser::array() noexcept { +inline simdjson_result auto_parser::array() & noexcept { return result(); } template -inline simdjson_result auto_parser::object() noexcept { +inline simdjson_result auto_parser::object() & noexcept { return result(); } @@ -236347,22 +250651,42 @@ inline simdjson_result auto_parser::number() noex #if SIMDJSON_EXCEPTIONS template template -inline auto_parser::operator T() noexcept(false) { - if (m_error != SUCCESS) { - throw simdjson_error(m_error); +inline auto_parser::operator T() & noexcept(false) { + // Use result() so direct-parse and deferred iterate both run. + T out; + error_code err = result().get(out); + if (err != SUCCESS) { + throw simdjson_error(err); } - return m_doc.get(); + return out; +} + +template +template +inline auto_parser::operator T() && noexcept(false) requires(!views_document) { + T out; + error_code err = result().get(out); + if (err != SUCCESS) { + throw simdjson_error(err); + } + return out; } #endif // SIMDJSON_EXCEPTIONS template template -inline std::optional auto_parser::optional() noexcept(is_nothrow_gettable) { +inline std::optional auto_parser::optional() && noexcept(is_nothrow_gettable) requires(!views_document) { + return optional(); +} + +template +template +inline std::optional auto_parser::optional() & noexcept(is_nothrow_gettable) { if (m_error != SUCCESS) { return std::nullopt; } T value; - if (m_doc.get().get(value)) [[unlikely]] { + if (result().get(value)) [[unlikely]] { return std::nullopt; } return {std::move(value)};