diff --git a/README.md b/README.md index 3d2bb960..037e4ca2 100644 --- a/README.md +++ b/README.md @@ -113,6 +113,25 @@ int main() // g++ -I./include/ -march=haswell --std=c++11 -O3 example/parse_and_serialize.cpp -o example/parse_and_serialize ``` +### Optional fast paths + +For C++17 builds, define either compiler macro consistently across all +translation units that use Sonic. Both are off by default. + +- `-DSONIC_ENABLE_PARSE_UINT_FASTPATH` specializes two unsigned integer shapes + in compact JSON: one- and two-digit object values and 16-digit array elements + immediately followed by a comma or the closing delimiter. +- `-DSONIC_ENABLE_SERIALIZE_OPT` batches quotes and backslashes in AVX2 string + serialization. It also exposes `WriteBuffer::ReleaseBuffer()` for transferring + the output allocation. Read `Size()` before the transfer and release the + returned pointer with `std::free`. Call `ToString()` before the transfer if + the consumer needs a null terminator. + +With the serialization macro enabled, pass +`SerializeFlags::kSerializeWriterStringGrowth` to `Serialize` to reserve +25% extra space when a string would grow the buffer to 1–64 MiB. This can +reduce later reallocations at the cost of higher capacity. + ### Checking parse result ```c++ #include "sonic/sonic.h" diff --git a/include/sonic/dom/flags.h b/include/sonic/dom/flags.h index 49134227..8cec69d9 100644 --- a/include/sonic/dom/flags.h +++ b/include/sonic/dom/flags.h @@ -68,6 +68,9 @@ enum class SerializeFlags : uint32_t { kSerializeInfNan = 1 << 3, kSerializeUnicodeEscapeUppercase = 1 << 4, kSerializeFloatFormatJava = 1 << 5, +#ifdef SONIC_ENABLE_SERIALIZE_OPT + kSerializeWriterStringGrowth = 1u << 31, +#endif }; // Compatibility layer for downstream users. diff --git a/include/sonic/dom/parser.h b/include/sonic/dom/parser.h index 05c2e163..4aeb7d49 100644 --- a/include/sonic/dom/parser.h +++ b/include/sonic/dom/parser.h @@ -220,6 +220,50 @@ class Parser { } } +#ifdef SONIC_ENABLE_PARSE_UINT_FASTPATH + template + sonic_force_inline bool tryContainerUint(uint8_t first, size_t &end, + uint64_t &value) const { + // The caller has consumed the first digit or minus sign. + if (first == '-' || pos_ >= len_) return false; + if constexpr (inObject) { + end = pos_; + value = first - '0'; + if (value != 0 && internal::is_digit(json_buf_[end])) { + value = value * 10 + (json_buf_[end] - '0'); + if (++end == len_) return false; + } + return json_buf_[end] == ',' || json_buf_[end] == '}'; + } else { + if (first == '0' || len_ - pos_ < 16) return false; + end = pos_ + 15; + if (json_buf_[end] != ',' && json_buf_[end] != ']') return false; + int digits = 16; + value = internal::simd_str2int( + reinterpret_cast(json_buf_ + pos_ - 1), digits); + return digits == 16; + } + } +#endif + + template + sonic_force_inline void parseContainerNumber(SAX &sax, uint8_t first) { +#ifdef SONIC_ENABLE_PARSE_UINT_FASTPATH + if constexpr (!(parseFlags & ParseFlags::kParseIntegerAsRaw)) { + size_t end; + uint64_t value; + if (tryContainerUint(first, end, value)) { + pos_ = end; + err_ = sax.Uint(value) ? kErrorNone : kSaxTermination; + return; + } + } +#else + (void)first; +#endif + parseNumber(sax); + } + template sonic_force_inline bool parseNumber(SAX &sax) { if constexpr (parseFlags & ParseFlags::kParseFloatAndOverflowNumAsNumStr) { @@ -871,7 +915,7 @@ class Parser { case '8': case '9': case '-': - parseNumber(sax); + parseContainerNumber(sax, c); sonic_check_err(); break; case 't': { @@ -966,7 +1010,7 @@ class Parser { case '8': case '9': case '-': - parseNumber(sax); + parseContainerNumber(sax, c); sonic_check_err(); break; case 't': { diff --git a/include/sonic/dom/serialize.h b/include/sonic/dom/serialize.h index d89327db..0c743ee1 100644 --- a/include/sonic/dom/serialize.h +++ b/include/sonic/dom/serialize.h @@ -32,6 +32,12 @@ namespace sonic_json { namespace internal { +#ifdef SONIC_ENABLE_SERIALIZE_OPT +#define SONIC_HAS_SERIALIZE_WRITER_STRING_GROWTH 1 +constexpr auto kSerializeWriterStringGrowth = + SerializeFlags::kSerializeWriterStringGrowth; +#endif + template sonic_force_inline SonicError SerializeImpl(const NodeType* node, WriteBuffer& wb) { @@ -51,7 +57,6 @@ sonic_force_inline SonicError SerializeImpl(const NodeType* node, uint32_t member_cnt = 0; uint32_t val_cnt, val_cnt_nxt; size_t str_len; - long inc_len; const char* str_ptr; ssize_t rn = 0; internal::Stack stk; @@ -79,8 +84,17 @@ sonic_force_inline SonicError SerializeImpl(const NodeType* node, case kString: { is_key = ((size_t)(is_obj) & (~val_cnt)); str_len = node->Size(); - inc_len = str_len * 6 + 32 + 3; - wb.Grow(inc_len); +#ifdef SONIC_ENABLE_SERIALIZE_OPT + if constexpr (serializeFlags & kSerializeWriterStringGrowth) { + if (str_len > (SIZE_MAX - 35) / 6 || + !wb.GrowForString(str_len * 6 + 35)) { + return kErrorNoMem; + } + } else +#endif + { + wb.Grow(str_len * 6 + 35); + } str_ptr = node->GetStringView().data(); rn = internal::Quote(str_ptr, str_len, wb.End()) - wb.End(); diff --git a/include/sonic/internal/arch/avx2/quote.h b/include/sonic/internal/arch/avx2/quote.h index 37cfc6ab..56c8d69e 100644 --- a/include/sonic/internal/arch/avx2/quote.h +++ b/include/sonic/internal/arch/avx2/quote.h @@ -43,6 +43,46 @@ namespace avx2 { using VecType = simd::simd256; +#ifdef SONIC_ENABLE_SERIALIZE_OPT +struct QuoteShuffleTable { + alignas(16) uint8_t rows[256][16]{}; + + constexpr QuoteShuffleTable() { + for (unsigned mask = 0; mask < 256; ++mask) { + auto &row = rows[mask]; + // PSHUFB clears output bytes whose index has its high bit set. + for (auto &lane : row) lane = 0x80; + unsigned out = 0; + for (unsigned i = 0; i < 8; ++i) { + if ((mask >> i) & 1u) row[out++] = 8; // Backslash from lane 8. + row[out++] = static_cast(i); + } + } + } +}; + +inline constexpr QuoteShuffleTable kQuoteShuffleTable{}; + +static sonic_force_inline char *QuoteSimpleEscapes32(const char *src, char *dst, + uint32_t mask) { + const __m128i backslashes = _mm_set1_epi8('\\'); + for (unsigned offset = 0; offset < 32; offset += 8) { + const unsigned group = mask & 0xff; + const __m128i input = + _mm_loadl_epi64(reinterpret_cast(src + offset)); + const __m128i bytes = _mm_unpacklo_epi64(input, backslashes); + const __m128i lanes = _mm_load_si128( + reinterpret_cast(kQuoteShuffleTable.rows[group])); + _mm_storeu_si128(reinterpret_cast<__m128i *>(dst), + _mm_shuffle_epi8(bytes, lanes)); + // The next group overwrites padding. Quote already requires SIMD slack. + dst += 8 + __builtin_popcount(group); + mask >>= 8; + } + return dst; +} +#endif + #include "../common/x86_common/quote.inc.h" } // namespace avx2 diff --git a/include/sonic/internal/arch/common/x86_common/quote.inc.h b/include/sonic/internal/arch/common/x86_common/quote.inc.h index 1a84f2d6..fe1a96ec 100644 --- a/include/sonic/internal/arch/common/x86_common/quote.inc.h +++ b/include/sonic/internal/arch/common/x86_common/quote.inc.h @@ -159,16 +159,21 @@ sonic_force_inline size_t parseStringInplace(uint8_t *&src, SonicError &err) { #undef SONIC_REPEAT8 } +struct EscapeMasks { + uint32_t all; + uint32_t control_or_emoji; +}; + template -static sonic_force_inline int CopyAndGetEscapMask(const char *src, char *dst) { +static sonic_force_inline EscapeMasks CopyAndGetEscapeMasks(const char *src, + char *dst) { VecType v(reinterpret_cast(src)); v.store(reinterpret_cast(dst)); - if constexpr (EscapeEmoji) { - return ((v < '\x20') | (v == '\\') | (v == '"') | (v >= '\xF0')) - .to_bitmask(); - } else { - return ((v < '\x20') | (v == '\\') | (v == '"')).to_bitmask(); - } + auto special = v < '\x20'; + if constexpr (EscapeEmoji) special = special | (v >= '\xF0'); + return { + static_cast((special | (v == '\\') | (v == '"')).to_bitmask()), + static_cast(special.to_bitmask())}; } template @@ -183,9 +188,17 @@ sonic_static_inline char *Quote(const char *src, size_t nb, char *dst) { /* VEC_LEN-byte loop */ while (nb >= VEC_LEN) { /* check for matches */ - // TODO: optimize: exploit the simd bitmask in the escape block. - if ((mm = CopyAndGetEscapMask(src, dst)) != 0) { - cn = __builtin_ctz(mm); + const auto masks = CopyAndGetEscapeMasks(src, dst); + if (masks.all != 0) { +#if defined(SONIC_ENABLE_SERIALIZE_OPT) && VEC_LEN == 32 + if (masks.control_or_emoji == 0) { + dst = QuoteSimpleEscapes32(src, dst, masks.all); + src += VEC_LEN; + nb -= VEC_LEN; + continue; + } +#endif + cn = __builtin_ctz(masks.all); MOVE_N_CHARS(src, cn); DoEscape(src, dst, nb); } else { @@ -209,7 +222,7 @@ sonic_static_inline char *Quote(const char *src, size_t nb, char *dst) { src_r = tmp_src; } while (nb > 0) { - mm = CopyAndGetEscapMask(src_r, dst) & + mm = CopyAndGetEscapeMasks(src_r, dst).all & (VEC_FULL_MASK >> (VEC_LEN - nb)); if (mm) { cn = __builtin_ctz(mm); diff --git a/include/sonic/internal/stack.h b/include/sonic/internal/stack.h index fa483065..4de0196f 100644 --- a/include/sonic/internal/stack.h +++ b/include/sonic/internal/stack.h @@ -16,6 +16,7 @@ #pragma once +#include #include #include @@ -68,6 +69,14 @@ class Stack { cap_ = new_cap; } +#ifdef SONIC_ENABLE_SERIALIZE_OPT + char* ReleaseBuffer() noexcept { + char* buffer = buf_; + setZero(); + return buffer; + } +#endif + /** * @brief Erases all contexts in the buffer. */ @@ -167,18 +176,31 @@ class Stack { * remained capacity in the buffer. Otherwise, do nothing. */ sonic_force_inline char* Grow(size_t cnt) { - if (sonic_unlikely(top_ + cnt >= buf_ + cap_)) { - if (sonic_unlikely((top_ + cnt) > buf_ + 2 * cap_)) { - size_t needed = (top_ - buf_) + cnt; - Reserve(needed + needed / 2); - } else { - Reserve(cap_ * 2); - } + if (sonic_unlikely(cnt >= cap_ - Size())) { + Reserve(GrowthCapacity(Size() + cnt)); } sonic_assert(buf_ != NULL); return top_; } +#ifdef SONIC_ENABLE_SERIALIZE_OPT + sonic_force_inline char* GrowForString(size_t cnt) { + const size_t size = Size(); + if (sonic_likely(cnt < cap_ - size) || cnt == 0) return top_; + if (sonic_unlikely(cnt > PTRDIFF_MAX - size)) return nullptr; + + const size_t needed = size + cnt; + const size_t target = GrowthCapacity(needed); + // Leave room for subsequent strings when the normal allocation is 1–64 MiB. + if (target >= (1u << 20) && target <= (64u << 20)) { + Reserve(target + target / 4); + if (cap_ >= needed) return top_; + } + Reserve(target > PTRDIFF_MAX ? needed : target); + return cap_ >= needed ? top_ : nullptr; + } +#endif + /** * @brief Get the end of the buffer. * @return the value pointer into the ending. @@ -206,6 +228,10 @@ class Stack { } private: + size_t GrowthCapacity(size_t needed) const { + return needed > 2 * cap_ ? needed + needed / 2 : 2 * cap_; + } + void setZero() { buf_ = nullptr; top_ = nullptr; diff --git a/include/sonic/macro.h b/include/sonic/macro.h index e1fb37ca..df51baf7 100644 --- a/include/sonic/macro.h +++ b/include/sonic/macro.h @@ -46,6 +46,10 @@ #define sonic_assert(x) assert((x)) #endif +#if defined(SONIC_ENABLE_SERIALIZE_OPT) && __cplusplus < 201703L +#error "SONIC_ENABLE_SERIALIZE_OPT requires C++17 or later." +#endif + #if __cplusplus >= 201703L #define SONIC_IF_CONSTEXPR constexpr #else diff --git a/include/sonic/writebuffer.h b/include/sonic/writebuffer.h index 95a8053b..80040663 100644 --- a/include/sonic/writebuffer.h +++ b/include/sonic/writebuffer.h @@ -21,6 +21,10 @@ #include "sonic/internal/stack.h" #include "sonic/string_view.h" +#ifdef SONIC_ENABLE_SERIALIZE_OPT +#define SONIC_HAS_WRITEBUFFER_RELEASE_BUFFER 1 +#endif + namespace sonic_json { class WriteBuffer { @@ -59,6 +63,13 @@ class WriteBuffer { sonic_force_inline size_t Capacity() const { return stack_.Capacity(); } sonic_force_inline bool Empty() const { return stack_.Empty(); } +#ifdef SONIC_ENABLE_SERIALIZE_OPT + // Transfer the allocation to the caller, who must std::free it. Capture + // Size() first to get the byte count. The buffer is empty and reusable + // afterwards. + char* ReleaseBuffer() noexcept { return stack_.ReleaseBuffer(); } +#endif + /** * @brief Increase the capacity of buffer if new_cap is greater than the * current capacity(). Otherwise, do nothing. @@ -139,6 +150,13 @@ class WriteBuffer { */ sonic_force_inline char* Grow(size_t cnt) { return stack_.Grow(cnt); } +#ifdef SONIC_ENABLE_SERIALIZE_OPT + // Returns nullptr on allocation failure, preserving the current contents. + sonic_force_inline char* GrowForString(size_t cnt) { + return stack_.GrowForString(cnt); + } +#endif + /** * @brief Get the end of the buffer. * @return the value pointer into the ending. diff --git a/tests/parsenumber_test.cpp b/tests/parsenumber_test.cpp index ae295932..76068c19 100644 --- a/tests/parsenumber_test.cpp +++ b/tests/parsenumber_test.cpp @@ -148,6 +148,50 @@ TEST(ParserTest, ParseNumber) { TestParseDouble(-1234567890123456789012345.0, "-1234567890123456789012345"); } +TEST(ParserTest, ContainerUnsignedIntegers) { + Document doc; + doc.Parse(R"({"a":0,"b":9,"c":10,"d":99,"e":100,"f":-1,"g":1.5,"h":42 })"); + ASSERT_FALSE(doc.HasParseError()); + EXPECT_EQ(doc["a"].GetUint64(), 0u); + EXPECT_EQ(doc["b"].GetUint64(), 9u); + EXPECT_EQ(doc["c"].GetUint64(), 10u); + EXPECT_EQ(doc["d"].GetUint64(), 99u); + EXPECT_EQ(doc["e"].GetUint64(), 100u); + EXPECT_EQ(doc["f"].GetInt64(), -1); + EXPECT_DOUBLE_EQ(doc["g"].GetDouble(), 1.5); + EXPECT_EQ(doc["h"].GetUint64(), 42u); + + doc.Parse( + "[1000000000000000,9999999999999999,100000000000000," + "10000000000000000,1000000000000000.5,1234567890123456]"); + ASSERT_FALSE(doc.HasParseError()); + ASSERT_EQ(doc.Size(), 6u); + EXPECT_EQ(doc[0].GetUint64(), 1000000000000000ULL); + EXPECT_EQ(doc[1].GetUint64(), 9999999999999999ULL); + EXPECT_EQ(doc[2].GetUint64(), 100000000000000ULL); + EXPECT_EQ(doc[3].GetUint64(), 10000000000000000ULL); + EXPECT_DOUBLE_EQ(doc[4].GetDouble(), 1000000000000000.5); + EXPECT_EQ(doc[5].GetUint64(), 1234567890123456ULL); + + for (const char* invalid : + {R"({"a":01})", "[0123456789012345]", "[100000000000000a]", + "[1234567890123456", R"({"a":99)"}) { + doc.Parse(invalid); + EXPECT_EQ(doc.GetParseError(), kParseErrorInvalidChar) << invalid; + } +} + +TEST(ParserTest, ContainerUnsignedIntegersAsRaw) { + Document doc; + doc.Parse( + R"({"short":42,"array":[1234567890123456]})"); + ASSERT_FALSE(doc.HasParseError()); + ASSERT_TRUE(doc["short"].IsRaw()); + EXPECT_EQ(doc["short"].GetRaw(), "42"); + ASSERT_TRUE(doc["array"][0].IsRaw()); + EXPECT_EQ(doc["array"][0].GetRaw(), "1234567890123456"); +} + TEST(ParserTest, ParseIntegerAsRaw) { { Document doc; diff --git a/tests/parser_oom_test.cpp b/tests/parser_oom_test.cpp index 39dc433b..e39e13f5 100644 --- a/tests/parser_oom_test.cpp +++ b/tests/parser_oom_test.cpp @@ -454,8 +454,8 @@ TEST(Parser, NestedNumberRejectionReportsSaxTermination) { const char* json; bool reject_double; } cases[] = { - {R"({"a":1})", false}, - {R"([1])", false}, + {R"({"a":1})", false}, {R"({"a":42})", false}, + {R"([1])", false}, {R"([1234567890123456])", false}, {R"({"a":1.5})", true}, }; for (const auto& c : cases) { @@ -468,7 +468,8 @@ TEST(Parser, NestedNumberRejectionReportsSaxTermination) { } Parser p; auto res = p.Parse(buf.data(), std::strlen(c.json), sax); - EXPECT_EQ(kSaxTermination, res.Error()); + EXPECT_EQ(kSaxTermination, res.Error()) << c.json; + EXPECT_EQ(std::strlen(c.json) - 1, res.Offset()) << c.json; } } diff --git a/tests/quote_test.cpp b/tests/quote_test.cpp index c8c818eb..8303c968 100644 --- a/tests/quote_test.cpp +++ b/tests/quote_test.cpp @@ -31,13 +31,12 @@ typedef struct quoteTests { std::string expect; } quoteTests; +template void TestQuote(const std::string& input, const std::string& expect) { size_t n = input.size(); auto buf = std::unique_ptr(new char[(n + 2) * 6 + 32]); - char* end = - Quote(input.data(), n, buf.get()); - *end = '\0'; - EXPECT_STREQ(buf.get(), expect.data()); + char* end = Quote(input.data(), n, buf.get()); + EXPECT_EQ(std::string(buf.get(), end), expect); } void TestQuoteEscapeEmoji(const char* input, size_t n, @@ -87,4 +86,34 @@ TEST(Quote, EscapeEmojiStopsAtEndOfInvalidTail) { std::string(expect, sizeof(expect))); } +TEST(Quote, SimpleEscapesAcrossGroupsAndBlocks) { + for (unsigned mask = 0; mask < 256; ++mask) { + SCOPED_TRACE(mask); + std::string input; + std::string expect = "\""; + for (unsigned i = 0; i < 65; ++i) { + char c = static_cast('a' + i % 26); + if ((mask >> (i % 8)) & 1u) { + c = i % 2 == 0 ? '"' : '\\'; + expect += '\\'; + } + input += c; + expect += c; + } + TestQuote(input, expect + '"'); + } +} + +TEST(Quote, MixedEscapesAcrossBlockBoundary) { + const std::string prefix(28, 'x'); + const std::string suffix(39, '\\'); + const std::string input = prefix + "\"\\\xF0\x9F\x98\x80\x1A" + suffix; + const std::string quoted_prefix = '"' + prefix + "\\\"\\\\"; + const std::string quoted_suffix = std::string(suffix.size() * 2, '\\') + '"'; + TestQuote(input, quoted_prefix + "\xF0\x9F\x98\x80\\u001a" + quoted_suffix); + TestQuote( + input, quoted_prefix + "\\uD83D\\uDE00\\u001A" + quoted_suffix); +} + } // namespace diff --git a/tests/writebuffer_test.cpp b/tests/writebuffer_test.cpp index 072ab5bb..81537b56 100644 --- a/tests/writebuffer_test.cpp +++ b/tests/writebuffer_test.cpp @@ -18,7 +18,12 @@ #include +#include + #include "sonic/internal/stack.h" +#ifdef SONIC_ENABLE_SERIALIZE_OPT +#include "sonic/sonic.h" +#endif namespace { @@ -64,6 +69,60 @@ TEST(WriteBuffer, Reserve) { EXPECT_TRUE(wb.Size() <= wb.Capacity()); } +#ifdef SONIC_ENABLE_SERIALIZE_OPT +TEST(WriteBuffer, ReleaseBufferTransfersOwnership) { + WriteBuffer wb; + wb.Push("a\0b", 3); + const size_t size = wb.Size(); + const char* original = wb.Begin(); + char* released = wb.ReleaseBuffer(); + ASSERT_EQ(original, released); + EXPECT_TRUE(wb.Empty()); + EXPECT_EQ(0u, wb.Capacity()); + EXPECT_EQ(nullptr, wb.ReleaseBuffer()); + EXPECT_EQ(nullptr, wb.GrowForString(0)); + + wb.Push("new", 3); + EXPECT_STREQ("new", wb.ToString()); + EXPECT_EQ(std::string("a\0b", 3), std::string(released, size)); + std::free(released); +} + +TEST(WriteBuffer, ZeroStringGrowthPreservesEmptyBuffer) { + WriteBuffer wb(0); + EXPECT_EQ(wb.Begin(), wb.GrowForString(0)); + EXPECT_EQ(0u, wb.Capacity()); + wb.Push('a'); + EXPECT_EQ("a", wb.ToStringView()); +} + +TEST(WriteBuffer, GrowForStringPreservesContentsOnFailure) { + WriteBuffer wb; + wb.Push("abc", 3); + const size_t capacity = wb.Capacity(); + EXPECT_EQ(nullptr, wb.GrowForString(SIZE_MAX)); + EXPECT_EQ(capacity, wb.Capacity()); + EXPECT_EQ("abc", wb.ToStringView()); +} + +TEST(WriteBuffer, StringGrowthIsOptInPerSerialization) { + for (const size_t length : {256u, 256u * 1024u}) { + const std::string value(length, 'x'); + Node node(value.data(), value.size()); + WriteBuffer normal; + WriteBuffer extra; + ASSERT_EQ(kErrorNone, node.Serialize(normal)); + ASSERT_EQ( + kErrorNone, + node.Serialize(extra)); + EXPECT_EQ(normal.ToStringView(), extra.ToStringView()); + const size_t capacity = normal.Capacity(); + EXPECT_EQ(length == 256 ? capacity : capacity + capacity / 4, + extra.Capacity()); + } +} +#endif + TEST(WriteBuffer, ToString) { { WriteBuffer wb;