Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
3 changes: 3 additions & 0 deletions include/sonic/dom/flags.h
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
48 changes: 46 additions & 2 deletions include/sonic/dom/parser.h
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,50 @@ class Parser {
}
}

#ifdef SONIC_ENABLE_PARSE_UINT_FASTPATH
template <bool inObject>
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<const char *>(json_buf_ + pos_ - 1), digits);
return digits == 16;
}
}
#endif

template <bool inObject, typename SAX>
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<inObject>(first, end, value)) {
pos_ = end;
err_ = sax.Uint(value) ? kErrorNone : kSaxTermination;
return;
}
}
#else
(void)first;
#endif
parseNumber(sax);
}

template <typename SAX>
sonic_force_inline bool parseNumber(SAX &sax) {
if constexpr (parseFlags & ParseFlags::kParseFloatAndOverflowNumAsNumStr) {
Expand Down Expand Up @@ -871,7 +915,7 @@ class Parser {
case '8':
case '9':
case '-':
parseNumber(sax);
parseContainerNumber<true>(sax, c);
sonic_check_err();
break;
case 't': {
Expand Down Expand Up @@ -966,7 +1010,7 @@ class Parser {
case '8':
case '9':
case '-':
parseNumber(sax);
parseContainerNumber<false>(sax, c);
sonic_check_err();
break;
case 't': {
Expand Down
20 changes: 17 additions & 3 deletions include/sonic/dom/serialize.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <SerializeFlags serializeFlags, typename NodeType>
sonic_force_inline SonicError SerializeImpl(const NodeType* node,
WriteBuffer& wb) {
Expand All @@ -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;
Expand Down Expand Up @@ -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<serializeFlags>(str_ptr, str_len, wb.End<char>()) -
wb.End<char>();
Expand Down
40 changes: 40 additions & 0 deletions include/sonic/internal/arch/avx2/quote.h
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,46 @@ namespace avx2 {

using VecType = simd::simd256<uint8_t>;

#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<uint8_t>(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<const __m128i *>(src + offset));
const __m128i bytes = _mm_unpacklo_epi64(input, backslashes);
const __m128i lanes = _mm_load_si128(
reinterpret_cast<const __m128i *>(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
Expand Down
35 changes: 24 additions & 11 deletions include/sonic/internal/arch/common/x86_common/quote.inc.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <bool EscapeEmoji>
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<const uint8_t *>(src));
v.store(reinterpret_cast<uint8_t *>(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<uint32_t>((special | (v == '\\') | (v == '"')).to_bitmask()),
static_cast<uint32_t>(special.to_bitmask())};
}

template <SerializeFlags serializeFlags>
Expand All @@ -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<EscapeEmoji>(src, dst)) != 0) {
cn = __builtin_ctz(mm);
const auto masks = CopyAndGetEscapeMasks<EscapeEmoji>(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<serializeFlags>(src, dst, nb);
} else {
Expand All @@ -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<EscapeEmoji>(src_r, dst) &
mm = CopyAndGetEscapeMasks<EscapeEmoji>(src_r, dst).all &
(VEC_FULL_MASK >> (VEC_LEN - nb));
if (mm) {
cn = __builtin_ctz(mm);
Expand Down
40 changes: 33 additions & 7 deletions include/sonic/internal/stack.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

#pragma once

#include <cstdint>
#include <cstdlib>
#include <cstring>

Expand Down Expand Up @@ -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.
*/
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down
4 changes: 4 additions & 0 deletions include/sonic/macro.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions include/sonic/writebuffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand Down
Loading