Compare commits

..
Author SHA1 Message Date
Niels Lohmann 22d2013b13 Binary readers and writers: faster UTF-8 checks of strings
With error_handler_t::strict (and replace/ignore), every string a binary
reader reads is checked for valid UTF-8, and every string a binary writer
writes. The readers used the byte-at-a-time decoder; the writers skipped
ASCII eight bytes at a time.

- New valid_utf8_string() decides strings of up to 16 ASCII bytes, most
  keys and many values, with one or two word tests, and checks longer
  strings 16 bytes at a time with the NEON/SSSE3 UTF-8 check the lexer
  uses (vector_utf8_valid_blocks: the same lookup, but quotes and control
  characters are ordinary characters). Other targets and JSON_NO_SIMD use
  valid_utf8_prefix() as before.
- The readers check strings with it (for one-byte character types) in an
  out-of-line function, so that reading without a check does not pay for
  its code.
- The writers' check_utf8() uses it, and the CBOR and MessagePack writers
  write a checked string of up to max_text_in_reservation characters in
  one reservation, as they write unchecked ones.

Signed-off-by: Niels Lohmann <mail@nlohmann.me>
2026-10-31 09:45:14 +01:00
8 changed files with 728 additions and 774 deletions

No files matched your search

+44 -206
View File
@@ -22,7 +22,6 @@
#include <bit> //byteswap #include <bit> //byteswap
#endif #endif
#include <nlohmann/detail/bit_ops.hpp>
#include <nlohmann/detail/exceptions.hpp> #include <nlohmann/detail/exceptions.hpp>
#include <nlohmann/detail/input/input_adapters.hpp> #include <nlohmann/detail/input/input_adapters.hpp>
#include <nlohmann/detail/input/json_sax.hpp> #include <nlohmann/detail/input/json_sax.hpp>
@@ -742,13 +741,11 @@ class binary_reader
bool get_cbor_negative_integer() bool get_cbor_negative_integer()
{ {
NumberType number{}; NumberType number{};
return get_number(number) && emit_cbor_negative_integer(number); if (JSON_HEDLEY_UNLIKELY(!get_number(number)))
{
return false;
} }
/// pass the CBOR negative integer -1 - @a number to the SAX parser
template<typename NumberType>
bool emit_cbor_negative_integer(const NumberType number)
{
// the value is -1 - number, which fits into number_integer_t // the value is -1 - number, which fits into number_integer_t
// whenever number does; the outer cast undoes the integral promotion // whenever number does; the outer cast undoes the integral promotion
// for number_integer_t types narrower than int // for number_integer_t types narrower than int
@@ -973,7 +970,7 @@ class binary_reader
case 0x95: case 0x95:
case 0x96: case 0x96:
case 0x97: case 0x97:
return enter_cbor_array(conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu)); return enter_array(conditional_static_cast<std::size_t>(static_cast<unsigned int>(current) & 0x1Fu));
case 0x98: // array (one-byte uint8_t for n follows) case 0x98: // array (one-byte uint8_t for n follows)
case 0x99: // array (two-byte uint16_t for n follow) case 0x99: // array (two-byte uint16_t for n follow)
@@ -982,7 +979,7 @@ class binary_reader
{ {
std::uint64_t len{}; std::uint64_t len{};
std::size_t size{}; std::size_t size{};
return get_cbor_argument(len) && get_cbor_container_size(len, size, "array") && enter_cbor_array(size); return get_cbor_argument(len) && get_cbor_container_size(len, size, "array") && enter_array(size);
} }
case 0x9F: // array (indefinite length) case 0x9F: // array (indefinite length)
@@ -1136,10 +1133,16 @@ class binary_reader
return get_half_float(false); return get_half_float(false);
case 0xFA: // Single-Precision Float (four-byte IEEE 754) case 0xFA: // Single-Precision Float (four-byte IEEE 754)
return get_cbor_float<float>(); {
float number{};
return get_number(number) && emit_float(number);
}
case 0xFB: // Double-Precision Float (eight-byte IEEE 754) case 0xFB: // Double-Precision Float (eight-byte IEEE 754)
return get_cbor_float<double>(); {
double number{};
return get_number(number) && emit_float(number);
}
default: // anything else (0xFF is handled inside the other types) default: // anything else (0xFF is handled inside the other types)
{ {
@@ -1148,16 +1151,6 @@ class binary_reader
} }
} }
/// read a single- or double-precision float (kept out of
/// parse_cbor_value, which is inlined into parse_cbor_internal)
template<typename NumberType>
JSON_HEDLEY_NEVER_INLINE
bool get_cbor_float()
{
NumberType number{};
return get_number(number) && emit_float(number);
}
/*! /*!
@brief reports a nested indefinite-length CBOR string or byte array @brief reports a nested indefinite-length CBOR string or byte array
@param[in] type_name name of the rejected string type @param[in] type_name name of the rejected string type
@@ -1683,157 +1676,6 @@ class binary_reader
return true; return true;
} }
/*!
@brief read a big-endian number of type @a NumberType at @a data
*/
template<typename NumberType>
NumberType load_big_endian(const unsigned char* data) const noexcept
{
NumberType result{};
std::memcpy(&result, data, sizeof(NumberType));
if (is_little_endian)
{
byte_swap(result);
}
return result;
}
/*!
@brief read the integers, floats, booleans, and nulls that follow in a
definite-length array, without the per-element bookkeeping of
@ref parse_cbor_internal
Stops at the end of the array, at any other kind of value, and when fewer
than 9 bytes (the longest of these values) are left in the input, leaving
those to @ref parse_cbor_value, which reads them the same way.
@param[in,out] remaining the number of elements of the array not yet read
@return whether the SAX parser accepted the values
*/
bool parse_cbor_scalar_run(std::size_t& remaining)
{
while (remaining != 0 && ia.bulk_remaining() >= 9)
{
const auto* const data = reinterpret_cast<const unsigned char*>(ia.bulk_data());
const unsigned char head = data[0];
std::size_t size = 0;
bool accepted = true;
switch (head)
{
case 0x18:
size = 2;
accepted = emit_unsigned(data[1]);
break;
case 0x19:
size = 3;
accepted = emit_unsigned(load_big_endian<std::uint16_t>(data + 1));
break;
case 0x1A:
size = 5;
accepted = emit_unsigned(load_big_endian<std::uint32_t>(data + 1));
break;
case 0x1B:
size = 9;
accepted = emit_unsigned(load_big_endian<std::uint64_t>(data + 1));
break;
case 0x38:
size = 2;
accepted = emit_cbor_negative_integer(data[1]);
break;
case 0x39:
size = 3;
accepted = emit_cbor_negative_integer(load_big_endian<std::uint16_t>(data + 1));
break;
case 0x3A:
size = 5;
accepted = emit_cbor_negative_integer(load_big_endian<std::uint32_t>(data + 1));
break;
case 0x3B:
size = 9;
accepted = emit_cbor_negative_integer(load_big_endian<std::uint64_t>(data + 1));
break;
case 0xF4:
size = 1;
accepted = sax->boolean(false);
break;
case 0xF5:
size = 1;
accepted = sax->boolean(true);
break;
case 0xF6:
size = 1;
accepted = sax->null();
break;
case 0xFA:
size = 5;
accepted = emit_float(load_big_endian<float>(data + 1));
break;
case 0xFB:
size = 9;
accepted = emit_float(load_big_endian<double>(data + 1));
break;
default:
if (head <= 0x17)
{
size = 1;
accepted = sax->number_unsigned(static_cast<number_unsigned_t>(head));
}
else if (head >= 0x20 && head <= 0x37)
{
size = 1;
accepted = sax->number_integer(static_cast<std::int8_t>(0x20 - 1 - head));
}
else
{
// any other value is read by parse_cbor_value
return true;
}
break;
}
// as if read by get() and get_number(): current is the head byte
ia.bulk_skip(size);
chars_read += size;
current = head;
--remaining;
if (JSON_HEDLEY_UNLIKELY(!accepted))
{
return false;
}
}
return true;
}
/*!
@brief open a definite-length array and read the scalars it begins with
(see @ref parse_cbor_scalar_run)
Only the start of an array is tried, which covers arrays of numbers
(e.g. coordinates) but costs arrays of other values only one test, not one
per element.
@param[in] len the number of elements
@return whether the SAX parser accepted the array and the values read
*/
bool enter_cbor_array(const std::size_t len)
{
return enter_array(len) && (len == 0 || parse_cbor_array_start(std::integral_constant<bool, bulk_scan> {}));
}
/// read the scalars the array just opened begins with; out of line, so
/// that @ref parse_cbor_value stays small enough to be inlined into
/// @ref parse_cbor_internal
JSON_HEDLEY_NEVER_INLINE
bool parse_cbor_array_start(std::true_type /*bulk*/)
{
return parse_cbor_scalar_run(container_stack.back().remaining);
}
/// input that is not contiguous: every value is read by parse_cbor_value
bool parse_cbor_array_start(std::false_type /*bulk*/) const noexcept
{
return true;
}
/*! /*!
@brief read a CBOR value and everything nested inside it @brief read a CBOR value and everything nested inside it
@@ -1863,7 +1705,6 @@ class binary_reader
// pop_back() below, which destroys the container_stack element // pop_back() below, which destroys the container_stack element
// it would otherwise alias // it would otherwise alias
const container_frame top = container_stack.back(); const container_frame top = container_stack.back();
const bool is_object = top.is_object;
bool at_end = false; bool at_end = false;
if (top.remaining != npos) if (top.remaining != npos)
@@ -1875,7 +1716,7 @@ class binary_reader
{ {
// claim the element about to be read // claim the element about to be read
--container_stack.back().remaining; --container_stack.back().remaining;
if (is_object) if (top.is_object)
{ {
get(); get();
} }
@@ -1888,7 +1729,7 @@ class binary_reader
// Testing for it consumes a byte, which is the first byte // Testing for it consumes a byte, which is the first byte
// of the next element when it is not one. // of the next element when it is not one.
at_end = (get() == 0xFF); at_end = (get() == 0xFF);
fetch = is_object; fetch = top.is_object;
} }
if (at_end) if (at_end)
@@ -1905,7 +1746,7 @@ class binary_reader
continue; continue;
} }
if (is_object) if (top.is_object)
{ {
if (JSON_HEDLEY_UNLIKELY(!skip_cbor_key_tags(tag_handler))) if (JSON_HEDLEY_UNLIKELY(!skip_cbor_key_tags(tag_handler)))
{ {
@@ -3850,13 +3691,13 @@ class binary_reader
return sax->null(); return sax->null();
case 0xFB: case 0xFB:
return sax->number_float(static_cast<number_float_t>(-1.0), no_source); return sax->number_float(static_cast<number_float_t>(-1.0), "");
case 0xFC: case 0xFC:
return sax->number_float(static_cast<number_float_t>(0.0), no_source); return sax->number_float(static_cast<number_float_t>(0.0), "");
case 0xFD: case 0xFD:
return sax->number_float(static_cast<number_float_t>(1.0), no_source); return sax->number_float(static_cast<number_float_t>(1.0), "");
case 0xFF: // empty string case 0xFF: // empty string
{ {
@@ -4225,27 +4066,6 @@ class binary_reader
return current; return current;
} }
/// reverse the byte order of a double with a single byteswap(): GCC does
/// not merge the byte-wise swap of the generic version into one
static void byte_swap(double& number) noexcept
{
static_assert(sizeof(double) == sizeof(std::uint64_t), "double must have 64 bits");
std::uint64_t bits{};
std::memcpy(&bits, &number, sizeof(bits));
bits = byteswap(bits);
std::memcpy(&number, &bits, sizeof(bits));
}
/// reverse the byte order of a float with a single byteswap()
static void byte_swap(float& number) noexcept
{
static_assert(sizeof(float) == sizeof(std::uint32_t), "float must have 32 bits");
std::uint32_t bits{};
std::memcpy(&bits, &number, sizeof(bits));
bits = byteswap(bits);
std::memcpy(&number, &bits, sizeof(bits));
}
template<class NumberType> template<class NumberType>
static void byte_swap(NumberType& number) static void byte_swap(NumberType& number)
{ {
@@ -4381,7 +4201,7 @@ class binary_reader
{ {
return out_of_range_error(exception_id::number_overflow, "number overflow", "value"); return out_of_range_error(exception_id::number_overflow, "number overflow", "value");
} }
return sax->number_float(result, no_source); return sax->number_float(result, "");
} }
/*! /*!
@@ -4441,7 +4261,7 @@ class binary_reader
}(); }();
return sax->number_float((half & 0x8000u) != 0 return sax->number_float((half & 0x8000u) != 0
? static_cast<number_float_t>(-val) ? static_cast<number_float_t>(-val)
: static_cast<number_float_t>(val), no_source); : static_cast<number_float_t>(val), "");
} }
/*! /*!
@@ -4473,6 +4293,19 @@ class binary_reader
return get_bytes(len, "string", result); return get_bytes(len, "string", result);
} }
/// whether @a s is valid UTF-8: ASCII eight bytes at a time, the rest
/// sequence by sequence (as the binary writers check strings)
static bool is_valid_utf8_string(const string_t& s, std::true_type /*is_byte*/) noexcept
{
return valid_utf8_string(reinterpret_cast<const unsigned char*>(s.data()), s.size());
}
/// whether @a s, of a character type wider than a byte, is valid UTF-8
static bool is_valid_utf8_string(const string_t& s, std::false_type /*is_byte*/) noexcept
{
return is_valid_utf8(s);
}
/*! /*!
@brief validate a decoded text string (value or object key) against @ref error_handler @brief validate a decoded text string (value or object key) against @ref error_handler
@@ -4492,7 +4325,16 @@ class binary_reader
*/ */
bool check_string_utf8(string_t& result, const char* context) bool check_string_utf8(string_t& result, const char* context)
{ {
if (error_handler == error_handler_t::keep || is_valid_utf8(result)) return error_handler == error_handler_t::keep || check_string_utf8_handler(result, context);
}
/// @ref check_string_utf8 for an error handler other than @ref
/// error_handler_t::keep; out of line, so that reading strings without a
/// check does not pay for the code of the check
JSON_HEDLEY_NEVER_INLINE
bool check_string_utf8_handler(string_t& result, const char* context)
{
if (is_valid_utf8_string(result, std::integral_constant<bool, sizeof(typename string_t::value_type) == 1>()))
{ {
return true; return true;
} }
@@ -4766,10 +4608,6 @@ class binary_reader
/// the SAX parser /// the SAX parser
json_sax_t* sax = nullptr; json_sax_t* sax = nullptr;
/// the (empty) source text of every number_float event: binary formats
/// have none, and a string_t built for each float would cost more
const string_t no_source{};
/// the containers that have been opened and not closed yet; see @ref container_frame /// the containers that have been opened and not closed yet; see @ref container_frame
std::vector<container_frame> container_stack{}; std::vector<container_frame> container_stack{};
@@ -322,6 +322,78 @@ JSON_SCAN_SSSE3_TARGET JSON_HEDLEY_NEVER_INLINE inline bool vector_utf8_run(cons
block_out = block; block_out = block;
return false; return false;
} }
/*!
@brief skip 16-byte blocks of well-formed UTF-8 at p (a character boundary)
Like vector_utf8_run, but quotes, backslashes, and control characters are
ordinary characters. Returns the start of the first block in which the check
found an error (which may belong to a sequence begun in the block before) or
where fewer than 16 bytes are left; a sequence may be cut at that point, so the
caller resumes at its start, one sequence at a time.
*/
JSON_SCAN_SSSE3_TARGET JSON_HEDLEY_NEVER_INLINE inline const unsigned char* vector_utf8_valid_blocks(const unsigned char* block, const unsigned char* e) noexcept
{
using lookup = utf8_lookup4<>;
#if JSON_SCAN_NEON
const uint8x16_t t1h = vld1q_u8(lookup::byte_1_high.data());
const uint8x16_t t1l = vld1q_u8(lookup::byte_1_low.data());
const uint8x16_t t2h = vld1q_u8(lookup::byte_2_high.data());
uint8x16_t prev = vdupq_n_u8(0);
while (e - block >= 16)
{
const uint8x16_t in = vld1q_u8(block);
if (vmaxvq_u8(vorrq_u8(in, prev)) < 0x80)
{
// ASCII here, and no sequence from the block before to finish
prev = in;
block += 16;
continue;
}
const uint8x16_t prev1 = vextq_u8(prev, in, 15);
const uint8x16_t sc = vandq_u8(vandq_u8(vqtbl1q_u8(t1h, vshrq_n_u8(prev1, 4)), vqtbl1q_u8(t1l, vandq_u8(prev1, vdupq_n_u8(0x0F)))), vqtbl1q_u8(t2h, vshrq_n_u8(in, 4)));
const uint8x16_t must23 = vorrq_u8(vqsubq_u8(vextq_u8(prev, in, 14), vdupq_n_u8(0xE0 - 0x80)), vqsubq_u8(vextq_u8(prev, in, 13), vdupq_n_u8(0xF0 - 0x80)));
const uint8x16_t err = veorq_u8(vandq_u8(must23, vdupq_n_u8(0x80)), sc);
if (vmaxvq_u8(err) != 0)
{
break;
}
prev = in;
block += 16;
}
#else
const __m128i t1h = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_1_high.data()))); // NOLINT(bugprone-casting-through-void)
const __m128i t1l = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_1_low.data()))); // NOLINT(bugprone-casting-through-void)
const __m128i t2h = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(lookup::byte_2_high.data()))); // NOLINT(bugprone-casting-through-void)
const __m128i nibble = _mm_set1_epi8(0x0F);
const __m128i zero = _mm_setzero_si128();
__m128i prev = zero;
while (e - block >= 16)
{
const __m128i in = _mm_loadu_si128(static_cast<const __m128i*>(static_cast<const void*>(block))); // NOLINT(bugprone-casting-through-void)
if (_mm_movemask_epi8(_mm_or_si128(in, prev)) == 0)
{
prev = in;
block += 16;
continue;
}
const __m128i prev1 = _mm_alignr_epi8(in, prev, 15);
const __m128i sc = _mm_and_si128(_mm_and_si128(_mm_shuffle_epi8(t1h, _mm_and_si128(_mm_srli_epi16(prev1, 4), nibble)),
_mm_shuffle_epi8(t1l, _mm_and_si128(prev1, nibble))),
_mm_shuffle_epi8(t2h, _mm_and_si128(_mm_srli_epi16(in, 4), nibble)));
const __m128i must23 = _mm_or_si128(_mm_subs_epu8(_mm_alignr_epi8(in, prev, 14), _mm_set1_epi8(0xE0 - 0x80)),
_mm_subs_epu8(_mm_alignr_epi8(in, prev, 13), _mm_set1_epi8(0xF0 - 0x80)));
const __m128i err = _mm_xor_si128(_mm_and_si128(must23, _mm_set1_epi8(static_cast<char>(-128))), sc);
if (_mm_movemask_epi8(_mm_cmpeq_epi8(err, zero)) != 0xFFFF)
{
break;
}
prev = in;
block += 16;
}
#endif
return block;
}
#endif #endif
} // namespace detail } // namespace detail
@@ -236,6 +236,64 @@ inline std::size_t valid_utf8_prefix(const unsigned char* data, std::size_t n) n
return pos; return pos;
} }
/*!
@brief whether [data, data+n) is valid UTF-8, for checking whole strings
The same answer as valid_utf8_prefix(data, n) == n. Short ASCII strings, the
most common keys and values, are decided in one test, and long strings are
checked 16 bytes at a time where the vector check is available.
*/
inline bool valid_utf8_string(const unsigned char* data, std::size_t n) noexcept
{
constexpr std::uint64_t high = 0x8080808080808080ull;
if (n <= 16)
{
// two overlapping words cover 8 to 16 bytes, one partial word fewer
std::uint64_t first = 0;
std::uint64_t last = 0;
if (n >= 8)
{
std::memcpy(&first, data, sizeof(first));
std::memcpy(&last, data + n - 8, sizeof(last));
}
else if (n != 0)
{
std::memcpy(&first, data, n);
}
if (((first | last) & high) == 0)
{
return true;
}
}
#if JSON_SCAN_VECTOR_UTF8
else if (n >= 32
#if JSON_SCAN_SSSE3_DISPATCH
&& cpu_has_ssse3()
#endif
)
{
const unsigned char* block = vector_utf8_valid_blocks(data, data + n);
// the rest from the start of a sequence that may be cut at block
for (int i = 1; i <= 3 && block - i >= data; ++i)
{
const unsigned char c = block[-i];
if (c < 0x80)
{
break;
}
if (c >= 0xC0)
{
block -= i;
break;
}
}
const auto checked = static_cast<std::size_t>(block - data);
return checked + valid_utf8_prefix(block, n - checked) == n;
}
#endif
return valid_utf8_prefix(data, n) == n;
}
#if JSON_SCAN_VECTOR_UTF8 #if JSON_SCAN_VECTOR_UTF8
/// the end of scan_string_vector from block, where the vector loop stopped /// the end of scan_string_vector from block, where the vector loop stopped
/// (ill-formed UTF-8, or fewer than 16 bytes left): one byte or sequence at a /// (ill-formed UTF-8, or fewer than 16 bytes left): one byte or sequence at a
@@ -3080,6 +3080,25 @@ class binary_writer
} }
} }
/// write the head and the characters of @a value, at most
/// max_text_in_reservation of them, in one reservation
JSON_HEDLEY_ALWAYS_INLINE void write_cbor_string_reserved(const string_t& value)
{
CharType* const out = oa.reserve(value.size() + 2);
CharType* p = out;
if (value.size() <= 0x17)
{
*p++ = to_char_type(static_cast<std::uint8_t>(0x60 + value.size()));
}
else
{
*p++ = to_char_type(0x78);
*p++ = to_char_type(static_cast<std::uint8_t>(value.size()));
}
copy_characters(p, reinterpret_cast<const CharType*>(value.data()), value.size());
oa.commit(static_cast<std::size_t>(p - out) + value.size());
}
/*! /*!
@brief write a CBOR text string @brief write a CBOR text string
@@ -3101,19 +3120,7 @@ class binary_writer
// the string is written as it is: head and characters in one reservation // the string is written as it is: head and characters in one reservation
if (JSON_HEDLEY_LIKELY(value.size() <= max_text_in_reservation)) if (JSON_HEDLEY_LIKELY(value.size() <= max_text_in_reservation))
{ {
CharType* const out = oa.reserve(value.size() + 2); write_cbor_string_reserved(value);
CharType* p = out;
if (value.size() <= 0x17)
{
*p++ = to_char_type(static_cast<std::uint8_t>(0x60 + value.size()));
}
else
{
*p++ = to_char_type(0x78);
*p++ = to_char_type(static_cast<std::uint8_t>(value.size()));
}
copy_characters(p, reinterpret_cast<const CharType*>(value.data()), value.size());
oa.commit(static_cast<std::size_t>(p - out) + value.size());
return; return;
} }
} }
@@ -3127,6 +3134,13 @@ class binary_writer
JSON_HEDLEY_NEVER_INLINE JSON_HEDLEY_NEVER_INLINE
void write_cbor_checked_string(const string_t& value, const BasicJsonType& context) void write_cbor_checked_string(const string_t& value, const BasicJsonType& context)
{ {
if (error_handler == error_handler_t::strict && value.size() <= max_text_in_reservation)
{
check_utf8(value, context);
write_cbor_string_reserved(value);
return;
}
string_t storage; string_t storage;
const string_t& sanitized = sanitize_utf8_for_write(value, context, storage); const string_t& sanitized = sanitize_utf8_for_write(value, context, storage);
@@ -3141,6 +3155,27 @@ class binary_writer
// MsgPack // // MsgPack //
///////////// /////////////
/// write the head and the characters of @a value, at most
/// max_text_in_reservation of them, in one reservation
JSON_HEDLEY_ALWAYS_INLINE void write_msgpack_string_reserved(const string_t& value)
{
CharType* const out = oa.reserve(value.size() + 2);
CharType* p = out;
if (value.size() <= 31)
{
// fixstr
*p++ = to_char_type(static_cast<std::uint8_t>(0xA0 | value.size()));
}
else
{
// str 8
*p++ = to_char_type(0xD9);
*p++ = to_char_type(static_cast<std::uint8_t>(value.size()));
}
copy_characters(p, reinterpret_cast<const CharType*>(value.data()), value.size());
oa.commit(static_cast<std::size_t>(p - out) + value.size());
}
/*! /*!
@brief write a MessagePack str @brief write a MessagePack str
@@ -3158,21 +3193,7 @@ class binary_writer
// the string is written as it is: head and characters in one reservation // the string is written as it is: head and characters in one reservation
if (JSON_HEDLEY_LIKELY(value.size() <= max_text_in_reservation)) if (JSON_HEDLEY_LIKELY(value.size() <= max_text_in_reservation))
{ {
CharType* const out = oa.reserve(value.size() + 2); write_msgpack_string_reserved(value);
CharType* p = out;
if (value.size() <= 31)
{
// fixstr
*p++ = to_char_type(static_cast<std::uint8_t>(0xA0 | value.size()));
}
else
{
// str 8
*p++ = to_char_type(0xD9);
*p++ = to_char_type(static_cast<std::uint8_t>(value.size()));
}
copy_characters(p, reinterpret_cast<const CharType*>(value.data()), value.size());
oa.commit(static_cast<std::size_t>(p - out) + value.size());
return; return;
} }
} }
@@ -3185,6 +3206,13 @@ class binary_writer
JSON_HEDLEY_NEVER_INLINE JSON_HEDLEY_NEVER_INLINE
void write_msgpack_checked_string(const string_t& value, const BasicJsonType& context) void write_msgpack_checked_string(const string_t& value, const BasicJsonType& context)
{ {
if (error_handler == error_handler_t::strict && value.size() <= max_text_in_reservation)
{
check_utf8(value, context);
write_msgpack_string_reserved(value);
return;
}
string_t storage; string_t storage;
const string_t& sanitized = sanitize_utf8_for_write(value, context, storage); const string_t& sanitized = sanitize_utf8_for_write(value, context, storage);
@@ -4794,10 +4822,9 @@ class binary_writer
static void check_utf8(const string_t& s, const BasicJsonType& context) static void check_utf8(const string_t& s, const BasicJsonType& context)
{ {
const auto* data = reinterpret_cast<const unsigned char*>(s.data()); const auto* data = reinterpret_cast<const unsigned char*>(s.data());
const std::size_t valid = valid_utf8_prefix(data, s.size()); if (JSON_HEDLEY_UNLIKELY(!valid_utf8_string(data, s.size())))
if (JSON_HEDLEY_UNLIKELY(valid != s.size()))
{ {
throw_invalid_utf8(data, valid, context); throw_invalid_utf8(data, valid_utf8_prefix(data, s.size()), context);
} }
} }
+457 -463
View File
File diff suppressed because it is too large. Load diff
-74
View File
@@ -29,9 +29,7 @@ using nlohmann::json;
#include "round_trip_corpus.hpp" #include "round_trip_corpus.hpp"
#include "test_utils.hpp" #include "test_utils.hpp"
#include "sax_countdown.hpp" #include "sax_countdown.hpp"
#include "sax_event_loggers.hpp"
using utils::SaxCountdown; using utils::SaxCountdown;
using utils::SaxEventLogger;
TEST_CASE("CBOR") TEST_CASE("CBOR")
@@ -2448,78 +2446,6 @@ TEST_CASE("CBOR SAX parsing stops at every event")
CHECK(count_events(std::vector<std::uint8_t>({0xBF, 0x61, 'a', 0x9F, 0x01, 0xFF, 0xFF})) == 6); CHECK(count_events(std::vector<std::uint8_t>({0xBF, 0x61, 'a', 0x9F, 0x01, 0xFF, 0xFF})) == 6);
} }
TEST_CASE("CBOR arrays of scalars from contiguous and non-contiguous input")
{
// contiguous input reads the integers, floats, booleans, and nulls an
// array begins with in one loop, other input value by value; both must
// give the same events, value, or error for the complete document and for
// every truncation of it, and stop at every event a SAX handler rejects
const std::vector<std::uint8_t> cbor =
{
0xA3, // map(3)
0x61, 'a', // "a"
0x98, 0x16, // array(22)
0x00, 0x17, 0x18, 0xFF, 0x19, 0x01, 0x00, // 0, 23, 255, 256
0x1A, 0x00, 0x01, 0x00, 0x00, // 65536
0x1B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 18446744073709551615
0x20, 0x37, 0x38, 0xFF, 0x39, 0x01, 0x00, // -1, -24, -256, -257
0x3A, 0x00, 0x01, 0x00, 0x00, // -65537
0x3B, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // -18446744073709551616 (a float)
0x3B, 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // -9223372036854775808
0xF4, 0xF5, 0xF6, // false, true, null
0xFA, 0x3F, 0xC0, 0x00, 0x00, // 1.5 (float32)
0xFB, 0xBF, 0xB9, 0x99, 0x99, 0x99, 0x99, 0x99, 0x9A, // -0.1
0xF9, 0x3C, 0x00, // 1.0 (float16, ends the loop)
0x01, 0x61, 'a', // 1, "a"
0xFB, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 2.5
0x61, 'b', // "b"
0x83, // array(3)
0x82, 0xFB, 0x3F, 0xF4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // [1.25,
0xFB, 0xC0, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // -3.75]
0x82, 0xFB, 0x3F, 0xF4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // [1.25,
0xFB, 0xC0, 0x0E, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // -3.75]
0x80, // []
0x61, 'c', // "c"
0x84, 0xA0, 0x01, 0xC1, 0x02, 0x81, 0x03 // [{}, 1, tag(1) 2, [3]]
};
const auto tags = json::cbor_tag_handler_t::ignore;
const json j = json::from_cbor(cbor, true, true, tags);
CHECK(j["a"].size() == 22);
CHECK(j["a"][5] == 18446744073709551615u);
CHECK(j["a"][11].is_number_float());
CHECK(j["a"][11] == -18446744073709551616.0);
CHECK(j["a"][12] == (std::numeric_limits<std::int64_t>::min)());
CHECK(j["a"][17] == -0.1);
CHECK(j["b"] == json::parse("[[1.25, -3.75], [1.25, -3.75], []]"));
CHECK(j["c"] == json::parse("[{}, 1, 2, [3]]"));
for (std::size_t length = 0; length <= cbor.size(); ++length)
{
CAPTURE(length)
const std::vector<std::uint8_t> contiguous(cbor.begin(), cbor.begin() + static_cast<std::ptrdiff_t>(length));
const std::list<std::uint8_t> bytewise(contiguous.begin(), contiguous.end());
CHECK(json::from_cbor(contiguous, true, false, tags).dump() == json::from_cbor(bytewise.begin(), bytewise.end(), true, false, tags).dump());
SaxEventLogger from_contiguous;
SaxEventLogger from_bytewise;
CHECK(json::sax_parse(contiguous, &from_contiguous, json::input_format_t::cbor, true, false, false, tags)
== json::sax_parse(bytewise.begin(), bytewise.end(), &from_bytewise, json::input_format_t::cbor, true, false, false, tags));
CHECK(from_contiguous.events == from_bytewise.events);
}
for (int events = 0; events <= 60; ++events)
{
CAPTURE(events)
const std::list<std::uint8_t> bytewise(cbor.begin(), cbor.end());
SaxCountdown from_contiguous(events);
SaxCountdown from_bytewise(events);
CHECK(json::sax_parse(cbor, &from_contiguous, json::input_format_t::cbor, true, false, false, tags)
== json::sax_parse(bytewise.begin(), bytewise.end(), &from_bytewise, json::input_format_t::cbor, true, false, false, tags));
}
}
TEST_CASE("CBOR indefinite-length strings do not recurse per chunk") TEST_CASE("CBOR indefinite-length strings do not recurse per chunk")
{ {
// Reading an indefinite-length string or byte array used to call itself // Reading an indefinite-length string or byte array used to call itself
+1
View File
@@ -403,6 +403,7 @@ TEST_CASE("guard page")
CHECK(nlohmann::detail::find_string_special(p, n) <= n); CHECK(nlohmann::detail::find_string_special(p, n) <= n);
CHECK(nlohmann::detail::find_ascii_copyable_run(p, n) <= n); CHECK(nlohmann::detail::find_ascii_copyable_run(p, n) <= n);
CHECK(nlohmann::detail::valid_utf8_prefix(p, n) <= n); CHECK(nlohmann::detail::valid_utf8_prefix(p, n) <= n);
CHECK(nlohmann::detail::valid_utf8_string(p, n) == (nlohmann::detail::valid_utf8_prefix(p, n) == n));
#if defined(JSON_USE_SIMDUTF) && defined(JSON_HAS_CPP_17) #if defined(JSON_USE_SIMDUTF) && defined(JSON_HAS_CPP_17)
CHECK(nlohmann::detail::find_string_delimiter(p, n) <= n); CHECK(nlohmann::detail::find_string_delimiter(p, n) <= n);
#endif #endif
+38
View File
@@ -13,6 +13,7 @@ using nlohmann::json;
#include <algorithm> #include <algorithm>
#include <fstream> #include <fstream>
#include <random>
#include <string> #include <string>
#include "make_test_data_available.hpp" #include "make_test_data_available.hpp"
#include "test_utils.hpp" #include "test_utils.hpp"
@@ -1631,3 +1632,40 @@ TEST_CASE("Unicode RFC 3629")
} }
DOCTEST_CLANG_SUPPRESS_WARNING_POP DOCTEST_CLANG_SUPPRESS_WARNING_POP
TEST_CASE("UTF-8 check of whole strings")
{
// valid_utf8_string() decides short strings with a word test and long ones
// 16 bytes at a time where a vector check is available; it must agree with
// the byte-wise check for every mix of ASCII, sequences of each length,
// ill-formed and truncated sequences, at every length and offset
const char* const pieces[] =
{
"a", "\x7F", "\xC3\xA9", "\xE2\x82\xAC", "\xE0\xA0\x80", "\xEF\xBF\xBF", "\xF0\x9F\x98\x80", "\xF4\x8F\xBF\xBF",
"\x80", "\xC0\xAF", "\xC3", "\xE2\x82", "\xED\xA0\x80", "\xF0\x9F", "\xF4\x90\x80\x80", "\xFF"
};
// std::mt19937's sequence is fixed by the standard; no distribution is used
std::mt19937 rng(5);
std::size_t valid = 0;
for (int i = 0; i < 100000; ++i)
{
std::string s;
const std::size_t length = rng() % 100;
const std::uint32_t ascii = rng() % 101;
while (s.size() < length)
{
// mostly well-formed pieces (the first eight), so that long valid
// strings are common
s += (rng() % 100 < ascii) ? std::string("x") : std::string(pieces[rng() % (rng() % 8 == 0 ? 16 : 8)]);
}
const auto* data = reinterpret_cast<const unsigned char*>(s.data());
const bool expected = nlohmann::detail::is_valid_utf8(s);
valid += expected ? 1 : 0;
CAPTURE(s)
CHECK(nlohmann::detail::valid_utf8_string(data, s.size()) == expected);
CHECK((nlohmann::detail::valid_utf8_prefix(data, s.size()) == s.size()) == expected);
}
// both outcomes are common enough to be tested
CHECK(valid > 20000);
CHECK(valid < 80000);
}