From 937deb8c0ebca6bf74531fac0f179687168ae159 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 08:41:42 +0100 Subject: [PATCH 1/4] Add record-level JSON streaming (StreamReader and StreamWriter) --- include/rfl/json.hpp | 1 + include/rfl/json/stream.hpp | 449 ++++++++++++++++++++++++++++++++++++ tests/json/test_stream.cpp | 335 +++++++++++++++++++++++++++ 3 files changed, 785 insertions(+) create mode 100644 include/rfl/json/stream.hpp create mode 100644 tests/json/test_stream.cpp diff --git a/include/rfl/json.hpp b/include/rfl/json.hpp index cac6b0e23..491ddd90a 100644 --- a/include/rfl/json.hpp +++ b/include/rfl/json.hpp @@ -8,6 +8,7 @@ #include "json/load.hpp" #include "json/read.hpp" #include "json/save.hpp" +#include "json/stream.hpp" #include "json/to_schema.hpp" #include "json/write.hpp" diff --git a/include/rfl/json/stream.hpp b/include/rfl/json/stream.hpp new file mode 100644 index 000000000..3684006d9 --- /dev/null +++ b/include/rfl/json/stream.hpp @@ -0,0 +1,449 @@ +#ifndef RFL_JSON_STREAM_HPP_ +#define RFL_JSON_STREAM_HPP_ + +#if __has_include() +#include +#else +#include "../thirdparty/yyjson.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../Processors.hpp" +#include "../Result.hpp" +#include "../internal/wrap_in_rfl_array_t.hpp" +#include "Parser.hpp" +#include "Reader.hpp" +#include "write.hpp" + +namespace rfl { +namespace json { + +/// Framing format for record-level JSON streaming. +enum class StreamFormat { + ndjson, ///< Newline-delimited JSON (`{...}\n{...}\n`). + json_seq, ///< RFC 7464 JSON Text Sequences (`\x1e{...}\n`). + json_array, ///< Top-level JSON array (`[{...},{...}]`). +}; + +/// Record-level streaming JSON writer. +template +class StreamWriter { + public: + explicit StreamWriter(std::ostream& _stream, + const StreamFormat _format = StreamFormat::ndjson, + const yyjson_write_flag _flag = 0) + : stream_(&_stream), format_(_format), flag_(_flag) {} + + StreamWriter(const StreamWriter&) = delete; + StreamWriter& operator=(const StreamWriter&) = delete; + + StreamWriter(StreamWriter&& _other) noexcept + : stream_(_other.stream_), + format_(_other.format_), + flag_(_other.flag_), + started_(_other.started_), + finished_(_other.finished_) { + _other.finished_ = true; + } + + StreamWriter& operator=(StreamWriter&&) = delete; + + ~StreamWriter() noexcept { + try { + finish(); + } catch (...) { + } + } + + /// Serializes one record and writes it immediately with framing. + void write(const auto& _obj) { + if (finished_) { + throw std::runtime_error("Cannot write to a finished StreamWriter."); + } + const auto encoded = rfl::json::write(_obj, flag_); + switch (format_) { + case StreamFormat::ndjson: + (*stream_) << encoded << '\n'; + break; + case StreamFormat::json_seq: + (*stream_) << '\x1e' << encoded << '\n'; + break; + case StreamFormat::json_array: + (*stream_) << (started_ ? ',' : '['); + started_ = true; + (*stream_) << encoded; + break; + } + } + + /// Finishes the stream (emits `[]` or `]` for `json_array`). Idempotent. + void finish() { + if (finished_) { + return; + } + finished_ = true; + if (format_ == StreamFormat::json_array) { + (*stream_) << (started_ ? "]" : "[]"); + } + } + + private: + std::ostream* stream_; + StreamFormat format_; + yyjson_write_flag flag_; + bool started_ = false; + bool finished_ = false; +}; + +/// Record-level streaming JSON reader. +template +class StreamReader { + public: + using ValueType = Result>; + + /// C++20 single-pass input iterator over streamed records. + class Iterator { + public: + using iterator_concept = std::input_iterator_tag; + using iterator_category = std::input_iterator_tag; + using value_type = ValueType; + using difference_type = std::ptrdiff_t; + + Iterator() noexcept = default; + explicit Iterator(StreamReader* _reader) noexcept : reader_(_reader) {} + + ValueType& operator*() const noexcept { return reader_->current_.value(); } + ValueType* operator->() const noexcept { + return &reader_->current_.value(); + } + + Iterator& operator++() { + if (reader_) { + reader_->current_ = reader_->next(); + if (!reader_->current_.has_value()) { + reader_ = nullptr; + } + } + return *this; + } + + void operator++(int) { ++(*this); } + + bool operator==(const Iterator&) const noexcept = default; + bool operator==(std::default_sentinel_t) const noexcept { + return reader_ == nullptr; + } + + private: + StreamReader* reader_ = nullptr; + }; + + explicit StreamReader(std::istream& _stream, + const StreamFormat _format = StreamFormat::ndjson, + const yyjson_read_flag _flag = 0, + const size_t _chunk_size = 65536) + : stream_(&_stream), + format_(_format), + flag_(_flag), + chunk_size_(_chunk_size > 0 ? _chunk_size : 1), + invalid_flag_((_flag & YYJSON_READ_INSITU) != 0) {} + + explicit StreamReader(const std::string_view _input, + const StreamFormat _format = StreamFormat::ndjson, + const yyjson_read_flag _flag = 0) + : stream_(nullptr), + format_(_format), + flag_(_flag), + chunk_size_(0), + buf_(_input), + eof_(true), + invalid_flag_((_flag & YYJSON_READ_INSITU) != 0) {} + + StreamReader(const StreamReader&) = delete; + StreamReader& operator=(const StreamReader&) = delete; + StreamReader(StreamReader&&) = default; + StreamReader& operator=(StreamReader&&) = default; + + /// Reads the next record, or returns `std::nullopt` at clean EOF. + std::optional next() { + if (done_) { + return std::nullopt; + } + if (invalid_flag_) { + return fail("YYJSON_READ_INSITU is not supported"); + } + switch (format_) { + case StreamFormat::ndjson: + return next_delimited(false); + case StreamFormat::json_seq: + return next_delimited(true); + case StreamFormat::json_array: + return next_array_element(); + } + done_ = true; + return std::nullopt; + } + + Iterator begin() { + current_ = next(); + return current_.has_value() ? Iterator(this) : Iterator(); + } + + Iterator end() const noexcept { return Iterator(); } + + private: + enum class ArrayState { before_open, expect_first, expect_sep_end, closed }; + + static bool is_json_ws(const char _c) noexcept { + return _c == ' ' || _c == '\t' || _c == '\n' || _c == '\r'; + } + + std::optional fail(const std::string& _msg) { + done_ = true; + return error(_msg); + } + + std::optional eof_or_io_error(const char* _eof_msg) { + done_ = true; + if (io_error_) { + return error("I/O error while reading JSON stream."); + } + return error(_eof_msg); + } + + void compact_buffer() { + if (pos_ == 0) { + return; + } + if (pos_ >= buf_.size()) { + buf_.clear(); + pos_ = 0; + } else if (stream_ != nullptr && + (pos_ >= chunk_size_ || pos_ * 2 >= buf_.size())) { + buf_.erase(0, pos_); + pos_ = 0; + } + } + + bool refill() { + if (eof_ || !stream_) { + eof_ = true; + return false; + } + compact_buffer(); + const size_t old_size = buf_.size(); + const size_t needed = old_size + chunk_size_; + if (buf_.capacity() < needed) { + buf_.reserve(std::max(needed, buf_.capacity() * 2)); + } + buf_.resize(needed); + stream_->read(buf_.data() + old_size, + static_cast(chunk_size_)); + const auto gcount = stream_->gcount(); + const size_t n = gcount > 0 ? static_cast(gcount) : size_t{0}; + buf_.resize(old_size + n); + if (stream_->bad()) { + io_error_ = true; + eof_ = true; + return false; + } + if (n == 0) { + eof_ = true; + return false; + } + if (stream_->eof()) { + eof_ = true; + } + return true; + } + + bool skip_ws(const bool _skip_rs = false) { + while (true) { + while (pos_ < buf_.size()) { + const char c = buf_[pos_]; + if (is_json_ws(c) || (_skip_rs && c == '\x1e')) { + ++pos_; + } else { + return true; + } + } + if (!refill()) { + return false; + } + } + } + + std::optional parse_next_value(const bool _allow_empty_eof) { + const yyjson_read_flag effective_flag = flag_ | YYJSON_READ_STOP_WHEN_DONE; + while (true) { + const size_t avail = buf_.size() - pos_; + if (avail == 0) { + if (!refill()) { + if (!io_error_ && _allow_empty_eof) { + done_ = true; + return std::nullopt; + } + return eof_or_io_error( + "Could not parse document: unexpected end of data"); + } + continue; + } + + yyjson_read_err err{}; + yyjson_doc* doc = yyjson_read_opts(buf_.data() + pos_, avail, + effective_flag, nullptr, &err); + if (doc) { + const size_t read_size = yyjson_doc_get_read_size(doc); + yyjson_val* root = yyjson_doc_get_root(doc); + const bool is_self_delimiting = + yyjson_is_ctn(root) || yyjson_is_str(root); + // Refill before committing bare primitives (e.g. `12` + `3`) at the + // exact buffer boundary when more bytes may still arrive. + if (!is_self_delimiting && pos_ + read_size == buf_.size() && !eof_) { + yyjson_doc_free(doc); + if (!refill() && io_error_) { + return fail("I/O error while reading JSON stream."); + } + continue; + } + + pos_ += read_size; + const auto r = Reader(); + auto res = + Parser>::read(r, Reader::InputVarType(root)); + yyjson_doc_free(doc); + compact_buffer(); + return res; + } + + const bool maybe_truncated = + (err.code == YYJSON_READ_ERROR_UNEXPECTED_END || + err.code == YYJSON_READ_ERROR_EMPTY_CONTENT); + if (maybe_truncated && !eof_) { + if (refill()) { + continue; + } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } + } + + done_ = true; + if (_allow_empty_eof && err.code == YYJSON_READ_ERROR_EMPTY_CONTENT) { + return std::nullopt; + } + return error("Could not parse document: " + + std::string(err.msg ? err.msg : "unknown error")); + } + } + + std::optional next_delimited(const bool _skip_rs) { + if (!skip_ws(_skip_rs)) { + done_ = true; + if (io_error_) { + return error("I/O error while reading JSON stream."); + } + return std::nullopt; + } + return parse_next_value(true); + } + + std::optional finish_array() { + ++pos_; // consume ']' + array_state_ = ArrayState::closed; + done_ = true; + if (skip_ws(false)) { + return error( + "Unexpected trailing content after closing ']' of JSON array."); + } + if (io_error_) { + return error("I/O error while reading JSON stream."); + } + return std::nullopt; + } + + std::optional next_array_element() { + if (array_state_ == ArrayState::before_open) { + if (!skip_ws(false)) { + return eof_or_io_error( + "Expected '[' at start of JSON array, got end of input."); + } + if (buf_[pos_] != '[') { + return fail("Expected '[' at start of JSON array."); + } + ++pos_; + array_state_ = ArrayState::expect_first; + } + + if (array_state_ == ArrayState::expect_first) { + if (!skip_ws(false)) { + return eof_or_io_error( + "Unexpected end of input in JSON array: expected ']' or value."); + } + if (buf_[pos_] == ']') { + return finish_array(); + } + auto res = parse_next_value(false); + if (!done_) { + array_state_ = ArrayState::expect_sep_end; + } + return res; + } + + if (array_state_ == ArrayState::expect_sep_end) { + if (!skip_ws(false)) { + return eof_or_io_error( + "Unexpected end of input in JSON array: expected ',' or ']'."); + } + if (buf_[pos_] == ']') { + return finish_array(); + } + if (buf_[pos_] != ',') { + return fail("Expected ',' or ']' in JSON array."); + } + ++pos_; // consume ',' + if (!skip_ws(false)) { + return eof_or_io_error( + "Unexpected end of input in JSON array after ','."); + } + if (buf_[pos_] == ']') { + if (flag_ & YYJSON_READ_ALLOW_TRAILING_COMMAS) { + return finish_array(); + } + return fail("Trailing comma is not allowed in JSON array."); + } + return parse_next_value(false); + } + + done_ = true; + return std::nullopt; + } + + std::istream* stream_; + StreamFormat format_; + yyjson_read_flag flag_; + size_t chunk_size_; + std::string buf_; + size_t pos_ = 0; + bool eof_ = false; + bool io_error_ = false; + bool done_ = false; + bool invalid_flag_ = false; + ArrayState array_state_ = ArrayState::before_open; + std::optional current_; +}; + +} // namespace json +} // namespace rfl + +#endif diff --git a/tests/json/test_stream.cpp b/tests/json/test_stream.cpp new file mode 100644 index 000000000..17c577516 --- /dev/null +++ b/tests/json/test_stream.cpp @@ -0,0 +1,335 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace test_stream { + +struct Row { + int id; + std::string name; + double score; + bool operator==(const Row&) const = default; +}; + +struct SnakeRow { + int user_id; + std::string first_name; + bool operator==(const SnakeRow&) const = default; +}; + +struct MoveOnlyRow { + int id; + std::unique_ptr label; +}; + +static_assert(std::input_iterator::Iterator>); +static_assert(std::ranges::input_range>); +static_assert( + std::input_iterator::Iterator>); + +template +std::vector collect_ok(rfl::json::StreamReader& _reader) { + std::vector out; + for (auto&& res : _reader) { + EXPECT_TRUE(res.has_value()) << (res.has_value() ? "" : res.error().what()); + if (res.has_value()) { + out.push_back(std::move(*res)); + } + } + return out; +} + +std::vector sample_rows() { + return { + Row{1, "Alice", 9.5}, + Row{2, "Bob", -3.25}, + Row{3, "Charlie\nLine2", 0.0}, + }; +} + +TEST(json, test_stream_ndjson_roundtrip) { + const auto expected = sample_rows(); + std::stringstream ss; + { + rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::ndjson); + for (const auto& row : expected) writer.write(row); + writer.finish(); + } + + const std::string payload = ss.str(); + EXPECT_NE(payload.find('\n'), std::string::npos); + + // istream overload via next() + std::istringstream in(payload); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + std::vector actual; + while (auto res = reader.next()) { + ASSERT_TRUE(res->has_value()) << res->error().what(); + actual.push_back(std::move(**res)); + } + EXPECT_EQ(actual, expected); + EXPECT_FALSE(reader.next().has_value()); + + // string_view overload via range-for + std::vector from_sv; + for (auto&& res : rfl::json::StreamReader( + std::string_view{payload}, rfl::json::StreamFormat::ndjson)) { + ASSERT_TRUE(res.has_value()) << res.error().what(); + from_sv.push_back(std::move(*res)); + } + EXPECT_EQ(from_sv, expected); +} + +TEST(json, test_stream_json_seq_roundtrip_and_consecutive_rs) { + const auto expected = sample_rows(); + std::stringstream ss; + { + rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::json_seq); + for (const auto& row : expected) writer.write(row); + } + ASSERT_FALSE(ss.str().empty()); + EXPECT_EQ(ss.str().front(), '\x1e'); + + std::istringstream in(ss.str()); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::json_seq); + EXPECT_EQ(collect_ok(reader), expected); + + // Consecutive \x1e, blank lines, and trailing empty sequences + const std::string messy = + "\x1e\x1e \n\x1e{\"id\":1,\"name\":\"A\",\"score\":1.5}\n" + "\x1e\n\x1e\t{\"id\":2,\"name\":\"B\",\"score\":2.5}\n\x1e\x1e "; + rfl::json::StreamReader messy_reader(std::string_view{messy}, + rfl::json::StreamFormat::json_seq); + EXPECT_EQ(collect_ok(messy_reader), + (std::vector{{1, "A", 1.5}, {2, "B", 2.5}})); +} + +TEST(json, test_stream_json_array_roundtrip_and_finish) { + const auto expected = sample_rows(); + std::stringstream ss; + { + rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::json_array); + for (const auto& row : expected) writer.write(row); + writer.finish(); + writer.finish(); // idempotent + EXPECT_THROW(writer.write(expected.front()), std::runtime_error); + } + + const std::string payload = ss.str(); + EXPECT_EQ(payload.front(), '['); + EXPECT_EQ(payload.back(), ']'); + + const auto full = rfl::json::read>(payload); + ASSERT_TRUE(full.has_value()) << full.error().what(); + EXPECT_EQ(*full, expected); + + std::istringstream in(payload); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::json_array); + EXPECT_EQ(collect_ok(reader), expected); + + // 0 records + destructor auto-finish emits "[]" + std::stringstream empty_ss; + { rfl::json::StreamWriter writer(empty_ss, rfl::json::StreamFormat::json_array); } + EXPECT_EQ(empty_ss.str(), "[]"); +} + +TEST(json, test_stream_empty_inputs) { + for (const std::string_view input : {"", " \n\t\r\n "}) { + std::istringstream in{std::string(input)}; + EXPECT_FALSE( + rfl::json::StreamReader(in, rfl::json::StreamFormat::ndjson) + .next() + .has_value()); + } + for (const std::string_view input : {"", "\x1e", "\x1e\x1e\n \x1e\t"}) { + EXPECT_FALSE( + rfl::json::StreamReader(input, rfl::json::StreamFormat::json_seq) + .next() + .has_value()); + } + for (const std::string_view input : {"[]", " [ \n\t ] "}) { + std::istringstream in{std::string(input)}; + EXPECT_FALSE( + rfl::json::StreamReader(in, rfl::json::StreamFormat::json_array) + .next() + .has_value()); + } + + // Empty string is not a valid json_array + rfl::json::StreamReader bad_empty(std::string_view{""}, + rfl::json::StreamFormat::json_array); + const auto res = bad_empty.next(); + ASSERT_TRUE(res.has_value()); + EXPECT_FALSE(res->has_value()); + EXPECT_FALSE(bad_empty.next().has_value()); +} + +TEST(json, test_stream_multiline_and_pretty_records) { + const auto expected = sample_rows(); + for (const auto fmt : + {rfl::json::StreamFormat::ndjson, rfl::json::StreamFormat::json_seq, + rfl::json::StreamFormat::json_array}) { + std::stringstream ss; + { + rfl::json::StreamWriter writer(ss, fmt, rfl::json::pretty); + for (const auto& row : expected) writer.write(row); + } + std::istringstream in(ss.str()); + rfl::json::StreamReader reader(in, fmt, 0, 13); + EXPECT_EQ(collect_ok(reader), expected); + } +} + +TEST(json, test_stream_tiny_chunks_primitives_and_objects) { + const std::vector expected_nums = {0.0, 123456.0, -987.625, 1.5e-4, + 42.0}; + const std::string ndjson_nums = "0\n123456\n-987.625\n1.5e-4\n42"; + const std::string array_nums = "[0, 123456, -987.625, 1.5e-4, 42]"; + + const std::vector expected_strs = { + "hello", "line1\nline2\t\"quoted\"", + "utf8: h\xc3\xa9llo \xf0\x9f\x8c\x8d", std::string(200, 'x')}; + std::stringstream str_ss; + { + rfl::json::StreamWriter writer(str_ss, rfl::json::StreamFormat::ndjson); + for (const auto& s : expected_strs) writer.write(s); + } + + const std::vector expected_rows = { + Row{100, std::string(256, 'a'), 1.25}, + Row{200, "h\xc3\xa9llo \xf0\x9f\x9a\x80", -99.5}, + }; + std::stringstream obj_ss; + { + rfl::json::StreamWriter writer(obj_ss, rfl::json::StreamFormat::json_array); + for (const auto& r : expected_rows) writer.write(r); + } + + for (const size_t chunk : {size_t{1}, size_t{3}, size_t{7}, size_t{13}}) { + { + std::istringstream in(ndjson_nums); + rfl::json::StreamReader r(in, rfl::json::StreamFormat::ndjson, 0, + chunk); + EXPECT_EQ(collect_ok(r), expected_nums) << "chunk=" << chunk; + } + { + std::istringstream in(array_nums); + rfl::json::StreamReader r(in, rfl::json::StreamFormat::json_array, + 0, chunk); + EXPECT_EQ(collect_ok(r), expected_nums) << "chunk=" << chunk; + } + { + std::istringstream in(str_ss.str()); + rfl::json::StreamReader r( + in, rfl::json::StreamFormat::ndjson, 0, chunk); + EXPECT_EQ(collect_ok(r), expected_strs) << "chunk=" << chunk; + } + { + std::istringstream in(obj_ss.str()); + rfl::json::StreamReader r(in, rfl::json::StreamFormat::json_array, 0, + chunk); + EXPECT_EQ(collect_ok(r), expected_rows) << "chunk=" << chunk; + } + } +} + +TEST(json, test_stream_processors_and_move_only) { + const std::vector expected = {{1, "Ada"}, {2, "Grace"}}; + std::stringstream ss; + { + rfl::json::StreamWriter writer(ss); + for (const auto& r : expected) writer.write(r); + } + EXPECT_NE(ss.str().find("\"userId\""), std::string::npos); + EXPECT_NE(ss.str().find("\"firstName\""), std::string::npos); + + std::istringstream in(ss.str()); + rfl::json::StreamReader reader(in); + EXPECT_EQ(collect_ok(reader), expected); + + // NoExtraFields rejects extra field on record 2 while keeping stream intact + const std::string mixed = + R"({"id":1,"name":"ok","score":1.0})" "\n" + R"({"id":2,"name":"bad","score":2.0,"extra":true})" "\n" + R"({"id":3,"name":"ok2","score":3.0})" "\n"; + rfl::json::StreamReader strict_reader{ + std::string_view{mixed}}; + const auto r1 = strict_reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, (Row{1, "ok", 1.0})); + const auto r2 = strict_reader.next(); + ASSERT_TRUE(r2.has_value()); + EXPECT_FALSE(r2->has_value()); + const auto r3 = strict_reader.next(); + ASSERT_TRUE(r3.has_value() && r3->has_value()); + EXPECT_EQ(**r3, (Row{3, "ok2", 3.0})); + EXPECT_FALSE(strict_reader.next().has_value()); + + // Move-only record type with range-for + const std::string move_json = + R"({"id":7,"label":"first"})" "\n" R"({"id":8,"label":"second"})" "\n"; + std::vector moved; + for (auto&& res : + rfl::json::StreamReader(std::string_view{move_json})) { + ASSERT_TRUE(res.has_value()) << res.error().what(); + moved.push_back(std::move(*res)); + } + ASSERT_EQ(moved.size(), 2u); + EXPECT_EQ(*moved[0].label, "first"); + EXPECT_EQ(*moved[1].label, "second"); +} + +TEST(json, test_stream_error_handling) { + // YYJSON_READ_INSITU rejected + { + rfl::json::StreamReader reader( + std::string_view{R"({"id":1,"name":"a","score":1.0})"}, + rfl::json::StreamFormat::ndjson, YYJSON_READ_INSITU); + const auto res = reader.next(); + ASSERT_TRUE(res.has_value()); + EXPECT_FALSE(res->has_value()); + EXPECT_FALSE(reader.next().has_value()); + } + + // Malformed and truncated ndjson + for (const std::string_view bad : + {std::string_view{"{bad}"}, std::string_view{R"({"id":1,"name":"a")"}}) { + std::istringstream in{std::string(bad)}; + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson, 0, + 3); + const auto res = reader.next(); + ASSERT_TRUE(res.has_value()); + EXPECT_FALSE(res->has_value()); + EXPECT_FALSE(reader.next().has_value()); + } + + // json_array framing errors + for (const std::string_view bad : + {"{}", "[", "[1, 2", "[1 2]", "[1,]", "[1,", "[] extra", "[1] extra"}) { + std::istringstream in{std::string(bad)}; + rfl::json::StreamReader reader( + in, rfl::json::StreamFormat::json_array, 0, 3); + bool saw_error = false; + int steps = 0; + while (auto res = reader.next()) { + ASSERT_LE(++steps, 10) << "Infinite loop on input: " << bad; + if (!res->has_value()) saw_error = true; + } + EXPECT_TRUE(saw_error) << "Expected error for input: " << bad; + } + + // Trailing comma allowed when YYJSON_READ_ALLOW_TRAILING_COMMAS is passed + rfl::json::StreamReader trailing(std::string_view{"[1, 2,]"}, + rfl::json::StreamFormat::json_array, + YYJSON_READ_ALLOW_TRAILING_COMMAS); + EXPECT_EQ(collect_ok(trailing), (std::vector{1, 2})); +} + +} // namespace test_stream From 82e3f1ff1e2af35f50182df7555b6e60c5ee986d Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 09:38:37 +0100 Subject: [PATCH 2/4] Address review blockers for JSON streaming (O(N) windowing, safety, recovery, docs) --- docs/content/supported_formats/json.md | 30 + include/rfl/json/stream.hpp | 844 +++++++++++++++++++++---- tests/json/test_stream.cpp | 560 +++++++++++++++- 3 files changed, 1311 insertions(+), 123 deletions(-) diff --git a/docs/content/supported_formats/json.md b/docs/content/supported_formats/json.md index e85d91c39..b0aada33f 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -78,6 +78,36 @@ Note that `std::cout` is also an ostream, so this works as well: rfl::json::write(person, std::cout) << std::endl; ``` +## Record-level streaming + +For large datasets or live streams, `rfl::json::StreamReader` and `rfl::json::StreamWriter` read and write one record at a time without loading the entire document into memory. Three framing formats are supported via `rfl::json::StreamFormat`: + +- `StreamFormat::ndjson` — Newline-delimited JSON (`{...}\n{...}\n`, default) +- `StreamFormat::json_seq` — RFC 7464 JSON Text Sequences (`\x1e{...}\n`) +- `StreamFormat::json_array` — Top-level JSON array (`[{...},{...}]`) + +```cpp +// Writing records incrementally +rfl::json::StreamWriter writer(my_ostream, rfl::json::StreamFormat::ndjson); +for (const auto& person : people) { + writer.write(person).value(); +} +writer.flush().value(); +writer.finish().value(); + +// Reading records incrementally (C++20 input_range or next()) +rfl::json::StreamReader reader(my_istream, rfl::json::StreamFormat::ndjson); +for (auto&& res : reader) { + if (res) { + process(*res); + } else { + log_error(res.error().what()); + } +} +``` + +`StreamReader` also accepts a `std::string_view` directly (zero-copy), supports processors such as `rfl::SnakeCaseToCamelCase` and `rfl::NoExtraFields`, enforces a configurable `max_record_bytes` cap (64 MiB default, `0` for unlimited), and recovers from per-record syntax errors in `ndjson` (advancing to the next line) and `json_seq` (resyncing to the next `\x1e`). `StreamWriter::write()`, `flush()`, and `finish()` return `rfl::Result`; pretty-printing flags are rejected for `ndjson` and `json_seq`. + ## Custom constructors One of the great things about C++ is that it gives you control over diff --git a/include/rfl/json/stream.hpp b/include/rfl/json/stream.hpp index 3684006d9..f24b92929 100644 --- a/include/rfl/json/stream.hpp +++ b/include/rfl/json/stream.hpp @@ -9,20 +9,27 @@ #include #include +#include +#include +#include #include #include +#include +#include #include #include -#include #include #include +#include #include #include "../Processors.hpp" #include "../Result.hpp" #include "../internal/wrap_in_rfl_array_t.hpp" +#include "../parsing/Parent.hpp" #include "Parser.hpp" #include "Reader.hpp" +#include "Writer.hpp" #include "write.hpp" namespace rfl { @@ -53,6 +60,7 @@ class StreamWriter { flag_(_other.flag_), started_(_other.started_), finished_(_other.finished_) { + _other.stream_ = nullptr; _other.finished_ = true; } @@ -60,41 +68,112 @@ class StreamWriter { ~StreamWriter() noexcept { try { - finish(); + (void)finish(); } catch (...) { } } /// Serializes one record and writes it immediately with framing. - void write(const auto& _obj) { + Result write(const auto& _obj) { if (finished_) { - throw std::runtime_error("Cannot write to a finished StreamWriter."); + return error("Cannot write to a finished StreamWriter."); } - const auto encoded = rfl::json::write(_obj, flag_); - switch (format_) { - case StreamFormat::ndjson: - (*stream_) << encoded << '\n'; - break; - case StreamFormat::json_seq: - (*stream_) << '\x1e' << encoded << '\n'; - break; - case StreamFormat::json_array: - (*stream_) << (started_ ? ',' : '['); - started_ = true; - (*stream_) << encoded; - break; + if ((format_ == StreamFormat::ndjson || + format_ == StreamFormat::json_seq) && + (flag_ & (YYJSON_WRITE_PRETTY | YYJSON_WRITE_PRETTY_TWO_SPACES | + YYJSON_WRITE_NEWLINE_AT_END)) != 0) { + return error( + "Pretty-printing and trailing newline flags are not allowed for " + "NDJSON or JSON Text Sequences."); + } + if (!stream_ || !stream_->good()) { + return error("Output stream is not in a good state."); + } + try { + using T = std::remove_cvref_t; + using ParentType = parsing::Parent; + auto w = Writer(); + Parser>::write(w, _obj, typename ParentType::Root{}); + yyjson_write_err err{}; + size_t len = 0; + const std::unique_ptr json_c_str( + yyjson_mut_write_opts(w.doc(), flag_, nullptr, &len, &err), + &std::free); + if (!json_c_str) { + return error("An error occurred while writing to JSON: " + + std::string(err.msg ? err.msg : "unknown error")); + } + switch (format_) { + case StreamFormat::ndjson: + stream_->write(json_c_str.get(), static_cast(len)); + stream_->put('\n'); + break; + case StreamFormat::json_seq: + stream_->put('\x1e'); + stream_->write(json_c_str.get(), static_cast(len)); + stream_->put('\n'); + break; + case StreamFormat::json_array: + stream_->put(started_ ? ',' : '['); + started_ = true; + stream_->write(json_c_str.get(), static_cast(len)); + break; + } + if (stream_->fail() || stream_->bad()) { + return error("I/O error while writing JSON record to stream."); + } + } catch (const std::exception& _e) { + return error(std::string("An error occurred while writing to JSON: ") + + _e.what()); } + return Nothing{}; + } + + /// Flushes the underlying output stream. + Result flush() { + if (!stream_) { + return error("StreamWriter has no output stream."); + } + if (stream_->fail() || stream_->bad()) { + return error("Output stream is not in a good state."); + } + try { + stream_->flush(); + if (stream_->fail() || stream_->bad()) { + return error("I/O error while flushing JSON stream."); + } + } catch (const std::exception& _e) { + return error(std::string("I/O error while flushing JSON stream: ") + + _e.what()); + } + return Nothing{}; } /// Finishes the stream (emits `[]` or `]` for `json_array`). Idempotent. - void finish() { + Result finish() { if (finished_) { - return; + return Nothing{}; } finished_ = true; - if (format_ == StreamFormat::json_array) { - (*stream_) << (started_ ? "]" : "[]"); + if (!stream_) { + return error("StreamWriter has no output stream."); + } + try { + if (format_ == StreamFormat::json_array) { + if (started_) { + stream_->put(']'); + } else { + stream_->write("[]", 2); + } + } + if (stream_->fail() || stream_->bad()) { + return error("I/O error while finishing JSON stream."); + } + } catch (const std::exception& _e) { + return error(std::string("I/O error while finishing JSON stream: ") + + _e.what()); } + return Nothing{}; } private: @@ -111,21 +190,21 @@ class StreamReader { public: using ValueType = Result>; + /// Default per-record memory cap (64 MiB). Pass `0` for unlimited. + static constexpr size_t kDefaultMaxRecordBytes = 64 * 1024 * 1024; + /// C++20 single-pass input iterator over streamed records. class Iterator { public: using iterator_concept = std::input_iterator_tag; - using iterator_category = std::input_iterator_tag; using value_type = ValueType; using difference_type = std::ptrdiff_t; Iterator() noexcept = default; explicit Iterator(StreamReader* _reader) noexcept : reader_(_reader) {} - ValueType& operator*() const noexcept { return reader_->current_.value(); } - ValueType* operator->() const noexcept { - return &reader_->current_.value(); - } + ValueType& operator*() const noexcept { return *reader_->current_; } + ValueType* operator->() const noexcept { return &(*reader_->current_); } Iterator& operator++() { if (reader_) { @@ -148,24 +227,28 @@ class StreamReader { StreamReader* reader_ = nullptr; }; - explicit StreamReader(std::istream& _stream, - const StreamFormat _format = StreamFormat::ndjson, - const yyjson_read_flag _flag = 0, - const size_t _chunk_size = 65536) + explicit StreamReader( + std::istream& _stream, const StreamFormat _format = StreamFormat::ndjson, + const yyjson_read_flag _flag = 0, const size_t _chunk_size = 65536, + const size_t _max_record_bytes = kDefaultMaxRecordBytes) : stream_(&_stream), format_(_format), flag_(_flag), chunk_size_(_chunk_size > 0 ? _chunk_size : 1), + max_record_bytes_(_max_record_bytes), invalid_flag_((_flag & YYJSON_READ_INSITU) != 0) {} - explicit StreamReader(const std::string_view _input, - const StreamFormat _format = StreamFormat::ndjson, - const yyjson_read_flag _flag = 0) + explicit StreamReader( + const std::string_view _input, + const StreamFormat _format = StreamFormat::ndjson, + const yyjson_read_flag _flag = 0, + const size_t _max_record_bytes = kDefaultMaxRecordBytes) : stream_(nullptr), format_(_format), flag_(_flag), chunk_size_(0), - buf_(_input), + max_record_bytes_(_max_record_bytes), + input_(_input), eof_(true), invalid_flag_((_flag & YYJSON_READ_INSITU) != 0) {} @@ -199,15 +282,38 @@ class StreamReader { return current_.has_value() ? Iterator(this) : Iterator(); } - Iterator end() const noexcept { return Iterator(); } + std::default_sentinel_t end() const noexcept { return std::default_sentinel; } private: + static constexpr size_t kInitialWindow = 4096; + enum class ArrayState { before_open, expect_first, expect_sep_end, closed }; + enum class SkipResult { found, eof, io_error, unclosed_comment }; static bool is_json_ws(const char _c) noexcept { return _c == ' ' || _c == '\t' || _c == '\n' || _c == '\r'; } + static size_t safe_double(const size_t _n) noexcept { + constexpr size_t kMax = std::numeric_limits::max(); + return _n > kMax / 2 ? kMax : _n * 2; + } + + static size_t safe_inc(const size_t _n) noexcept { + constexpr size_t kMax = std::numeric_limits::max(); + return _n < kMax ? _n + 1 : kMax; + } + + const char* data_ptr() const noexcept { + return stream_ ? buf_.data() : input_.data(); + } + + size_t data_size() const noexcept { + return stream_ ? buf_.size() : input_.size(); + } + + size_t avail() const noexcept { return data_size() - pos_; } + std::optional fail(const std::string& _msg) { done_ = true; return error(_msg); @@ -222,76 +328,527 @@ class StreamReader { } void compact_buffer() { - if (pos_ == 0) { + if (!stream_ || pos_ == 0) { return; } if (pos_ >= buf_.size()) { buf_.clear(); pos_ = 0; - } else if (stream_ != nullptr && - (pos_ >= chunk_size_ || pos_ * 2 >= buf_.size())) { + } else if (pos_ >= chunk_size_ || pos_ * 2 >= buf_.size()) { buf_.erase(0, pos_); pos_ = 0; } } - bool refill() { + /// Reads up to `_requested` bytes from `*stream_` without blocking past the + /// first available OS read (or first line terminator on unbuffered streams). + size_t refill_raw(const size_t _requested, const bool _line_mode, + const bool _stop_at_rs) { if (eof_ || !stream_) { eof_ = true; - return false; + return 0; + } + if (_requested == 0) { + return 0; + } + if (stream_->bad() || (stream_->fail() && !stream_->eof())) { + io_error_ = true; + eof_ = true; + return 0; + } + std::streambuf* sb = stream_->rdbuf(); + if (!sb) { + eof_ = true; + return 0; } + compact_buffer(); const size_t old_size = buf_.size(); - const size_t needed = old_size + chunk_size_; - if (buf_.capacity() < needed) { - buf_.reserve(std::max(needed, buf_.capacity() * 2)); - } - buf_.resize(needed); - stream_->read(buf_.data() + old_size, - static_cast(chunk_size_)); - const auto gcount = stream_->gcount(); - const size_t n = gcount > 0 ? static_cast(gcount) : size_t{0}; - buf_.resize(old_size + n); - if (stream_->bad()) { + const size_t max_string_add = buf_.max_size() - old_size; + const size_t max_stream_add = + static_cast(std::numeric_limits::max()); + const size_t to_read = + std::min({_requested, max_string_add, max_stream_add}); + if (to_read == 0) { + return 0; + } + + using Traits = std::istream::traits_type; + auto drain_available = [&](const size_t _limit) -> size_t { + if (_limit == 0) { + return 0; + } + const std::streamsize avail_now = sb->in_avail(); + if (avail_now < 0) { + eof_ = true; + return 0; + } + if (avail_now == 0) { + return 0; + } + const size_t n_want = std::min(_limit, static_cast(avail_now)); + const size_t cur = buf_.size(); + const size_t needed = cur + n_want; + if (buf_.capacity() < needed) { + const size_t doubled = safe_double(buf_.capacity()); + buf_.reserve(std::min(buf_.max_size(), std::max(needed, doubled))); + } + buf_.resize(needed); + const std::streamsize got = + sb->sgetn(buf_.data() + cur, static_cast(n_want)); + const size_t n_got = got > 0 ? static_cast(got) : size_t{0}; + buf_.resize(cur + n_got); + return n_got; + }; + + size_t total_got = 0; + try { + const std::streamsize initial_avail = sb->in_avail(); + if (initial_avail < 0) { + eof_ = true; + return 0; + } + if (initial_avail > 0) { + total_got = drain_available(to_read); + } else { + // Nothing buffered: block once for the first byte. + const auto ch = sb->sbumpc(); + if (Traits::eq_int_type(ch, Traits::eof())) { + eof_ = true; + if (stream_->bad()) { + io_error_ = true; + } + return 0; + } + const char first = Traits::to_char_type(ch); + buf_.push_back(first); + total_got = 1; + + if (!(_line_mode && first == '\n') && to_read > 1) { + const std::streamsize after_avail = sb->in_avail(); + if (after_avail > 0) { + total_got += drain_available(to_read - 1); + } else if (after_avail == 0 && _line_mode) { + // Unbuffered stream in line mode: read up to '\n' (or '\x1e'). + while (total_got < to_read) { + const auto next_ch = sb->sbumpc(); + if (Traits::eq_int_type(next_ch, Traits::eof())) { + eof_ = true; + break; + } + const char c = Traits::to_char_type(next_ch); + buf_.push_back(c); + ++total_got; + if (c == '\n' || (_stop_at_rs && c == '\x1e')) { + break; + } + } + } + } + } + } catch (...) { io_error_ = true; eof_ = true; - return false; + return 0; } - if (n == 0) { + + if (stream_->bad()) { + io_error_ = true; eof_ = true; + return 0; + } + return total_got; + } + + /// Refills while enforcing `max_record_bytes_` (allowing 1 lookahead byte + /// for delimiters after a record of exact size `max_record_bytes_`). + size_t refill_for_record(const size_t _requested, const bool _line_mode, + const bool _stop_at_rs) { + size_t allowed = _requested; + if (max_record_bytes_ > 0) { + const size_t cap = safe_inc(max_record_bytes_); + const size_t cur_avail = avail(); + if (cur_avail >= cap) { + record_too_large_ = true; + return 0; + } + allowed = std::min(allowed, cap - cur_avail); + } + return refill_raw(allowed, _line_mode, _stop_at_rs); + } + + bool skip_bom_if_needed() { + if (bom_checked_) { + return true; + } + bom_checked_ = true; + if ((flag_ & YYJSON_READ_ALLOW_BOM) == 0) { + return true; + } + const bool line_mode = (format_ != StreamFormat::json_array); + const bool stop_at_rs = (format_ == StreamFormat::json_seq); + if (avail() == 0 && !eof_) { + refill_raw(chunk_size_, line_mode, stop_at_rs); + if (io_error_) { + return false; + } + } + if (avail() == 0 || + static_cast(data_ptr()[pos_]) != 0xEF) { + return true; + } + while (avail() < 3 && !eof_) { + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + break; + } + } + if (io_error_) { return false; } - if (stream_->eof()) { - eof_ = true; + if (avail() >= 3 && + static_cast(data_ptr()[pos_]) == 0xEF && + static_cast(data_ptr()[pos_ + 1]) == 0xBB && + static_cast(data_ptr()[pos_ + 2]) == 0xBF) { + pos_ += 3; + compact_buffer(); } return true; } - bool skip_ws(const bool _skip_rs = false) { + SkipResult skip_ws(const bool _skip_rs = false) { + if (!skip_bom_if_needed()) { + return SkipResult::io_error; + } + const bool allow_comments = (flag_ & YYJSON_READ_ALLOW_COMMENTS) != 0; + const bool line_mode = (format_ != StreamFormat::json_array); + const bool stop_at_rs = (format_ == StreamFormat::json_seq); + while (true) { - while (pos_ < buf_.size()) { - const char c = buf_[pos_]; + while (pos_ < data_size()) { + const char c = data_ptr()[pos_]; if (is_json_ws(c) || (_skip_rs && c == '\x1e')) { ++pos_; - } else { - return true; + continue; } + if (allow_comments && c == '/') { + while (avail() < 2 && !eof_) { + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + break; + } + } + if (io_error_) { + return SkipResult::io_error; + } + if (avail() < 2) { + return SkipResult::found; + } + const char next_c = data_ptr()[pos_ + 1]; + if (next_c == '/') { + pos_ += 2; + while (true) { + while (pos_ < data_size()) { + const char cc = data_ptr()[pos_]; + if (cc == '\n' || cc == '\r') { + break; + } + ++pos_; + } + if (pos_ < data_size()) { + break; + } + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + return io_error_ ? SkipResult::io_error : SkipResult::eof; + } + } + continue; + } + if (next_c == '*') { + pos_ += 2; + bool closed = false; + while (!closed) { + while (pos_ < data_size()) { + if (data_ptr()[pos_] == '*') { + if (pos_ + 1 >= data_size()) { + if (eof_) { + return SkipResult::unclosed_comment; + } + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + return io_error_ ? SkipResult::io_error + : SkipResult::unclosed_comment; + } + continue; + } + if (data_ptr()[pos_ + 1] == '/') { + pos_ += 2; + closed = true; + break; + } + } + ++pos_; + } + if (!closed) { + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + return io_error_ ? SkipResult::io_error + : SkipResult::unclosed_comment; + } + } + } + continue; + } + } + return SkipResult::found; } - if (!refill()) { - return false; + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + return io_error_ ? SkipResult::io_error : SkipResult::eof; + } + } + } + + void advance_past_newline() { + const char* ptr = data_ptr() + pos_; + const size_t cur_avail = avail(); + if (const char* nl = + static_cast(std::memchr(ptr, '\n', cur_avail))) { + pos_ += static_cast(nl - ptr) + 1; + compact_buffer(); + return; + } + pos_ = data_size(); + compact_buffer(); + while (!eof_) { + if (refill_raw(chunk_size_, true, false) == 0) { + break; + } + const char* p = data_ptr() + pos_; + const size_t a = avail(); + if (const char* nl = static_cast(std::memchr(p, '\n', a))) { + pos_ += static_cast(nl - p) + 1; + compact_buffer(); + return; + } + pos_ = data_size(); + compact_buffer(); + } + } + + void resync_to_rs() { + const char* ptr = data_ptr() + pos_; + const size_t cur_avail = avail(); + if (cur_avail > 1) { + if (const char* rs = static_cast( + std::memchr(ptr + 1, '\x1e', cur_avail - 1))) { + pos_ += static_cast(rs - ptr); + compact_buffer(); + return; + } + } + pos_ = data_size(); + compact_buffer(); + while (!eof_) { + if (refill_raw(chunk_size_, true, true) == 0) { + break; + } + const char* p = data_ptr() + pos_; + const size_t a = avail(); + if (const char* rs = + static_cast(std::memchr(p, '\x1e', a))) { + pos_ += static_cast(rs - p); + compact_buffer(); + return; + } + pos_ = data_size(); + compact_buffer(); + } + } + + std::optional parse_delimited_value(const bool _is_seq) { + const yyjson_read_flag effective_flag = flag_ | YYJSON_READ_STOP_WHEN_DONE; + record_too_large_ = false; + size_t window = kInitialWindow; + size_t refill_step = chunk_size_; + bool expanded = false; + + while (true) { + if (avail() == 0) { + if (refill_for_record(refill_step, true, _is_seq) == 0) { + if (record_too_large_) { + return fail("JSON record exceeds maximum allowed size."); + } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } + done_ = true; + return std::nullopt; + } + continue; + } + + const char* ptr = data_ptr() + pos_; + const size_t cur_avail = avail(); + + const size_t probe_len = std::min(cur_avail, window); + const char* rs_ptr = + _is_seq + ? static_cast(std::memchr(ptr, '\x1e', probe_len)) + : nullptr; + const size_t nl_search_len = + rs_ptr ? static_cast(rs_ptr - ptr) : probe_len; + const char* nl_ptr = + !expanded + ? static_cast(std::memchr(ptr, '\n', nl_search_len)) + : nullptr; + + size_t slice_len = 0; + bool hard_boundary = false; + + if (nl_ptr) { + slice_len = static_cast(nl_ptr - ptr) + 1; + hard_boundary = false; + } else if (rs_ptr) { + slice_len = static_cast(rs_ptr - ptr); + hard_boundary = true; + } else if (!expanded && !eof_ && cur_avail < window) { + if (refill_for_record(refill_step, true, _is_seq) > 0) { + continue; + } + if (record_too_large_) { + return fail("JSON record exceeds maximum allowed size."); + } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } + slice_len = avail(); + hard_boundary = true; + } else { + slice_len = probe_len; + hard_boundary = (slice_len == cur_avail && eof_); + } + + bool hit_size_cap = false; + if (max_record_bytes_ > 0) { + const size_t allowed_slice = safe_inc(max_record_bytes_); + if (slice_len > allowed_slice) { + slice_len = allowed_slice; + hit_size_cap = true; + hard_boundary = false; + } else if (slice_len == allowed_slice && !nl_ptr && !rs_ptr && + !(slice_len == cur_avail && eof_)) { + hit_size_cap = true; + } + } + + if (slice_len == 0) { + if (hit_size_cap) { + return fail("JSON record exceeds maximum allowed size."); + } + done_ = true; + return std::nullopt; + } + + yyjson_read_err err{}; + yyjson_doc* doc = yyjson_read_opts(const_cast(ptr), slice_len, + effective_flag, nullptr, &err); + if (doc) { + const size_t read_size = yyjson_doc_get_read_size(doc); + yyjson_val* root = yyjson_doc_get_root(doc); + const bool is_self_delimiting = + yyjson_is_ctn(root) || yyjson_is_str(root); + + if (!is_self_delimiting && read_size == slice_len && !hard_boundary) { + yyjson_doc_free(doc); + if (hit_size_cap || + (max_record_bytes_ > 0 && read_size > max_record_bytes_)) { + return fail("JSON record exceeds maximum allowed size."); + } + expanded = true; + if (slice_len < cur_avail) { + window = std::max(safe_double(slice_len), safe_double(window)); + } else if (!eof_) { + refill_step = safe_double(refill_step); + window = std::max(safe_double(slice_len), window); + if (refill_for_record(refill_step, true, _is_seq) == 0) { + if (record_too_large_) { + return fail("JSON record exceeds maximum allowed size."); + } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } + } + } + continue; + } + + if (max_record_bytes_ > 0 && read_size > max_record_bytes_) { + yyjson_doc_free(doc); + return fail("JSON record exceeds maximum allowed size."); + } + + pos_ += read_size; + const auto r = Reader(); + auto res = + Parser>::read(r, Reader::InputVarType(root)); + yyjson_doc_free(doc); + compact_buffer(); + return res; + } + + const bool maybe_truncated = + (err.code == YYJSON_READ_ERROR_UNEXPECTED_END || + err.code == YYJSON_READ_ERROR_EMPTY_CONTENT); + + if (maybe_truncated) { + if (hit_size_cap || + (max_record_bytes_ > 0 && slice_len >= safe_inc(max_record_bytes_))) { + return fail("JSON record exceeds maximum allowed size."); + } + if (!hard_boundary) { + expanded = true; + if (slice_len < cur_avail) { + window = std::max(safe_double(slice_len), safe_double(window)); + continue; + } + if (!eof_) { + refill_step = safe_double(refill_step); + window = std::max(safe_double(slice_len), safe_double(window)); + if (refill_for_record(refill_step, true, _is_seq) > 0) { + continue; + } + if (record_too_large_) { + return fail("JSON record exceeds maximum allowed size."); + } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } + } + } + } + + const std::string err_msg = + "Could not parse document: " + + std::string(err.msg ? err.msg : "unknown error"); + if (_is_seq) { + resync_to_rs(); + } else { + advance_past_newline(); } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } + return error(err_msg); } } - std::optional parse_next_value(const bool _allow_empty_eof) { + std::optional parse_array_value() { const yyjson_read_flag effective_flag = flag_ | YYJSON_READ_STOP_WHEN_DONE; + record_too_large_ = false; + size_t window = kInitialWindow; + size_t refill_step = chunk_size_; + while (true) { - const size_t avail = buf_.size() - pos_; - if (avail == 0) { - if (!refill()) { - if (!io_error_ && _allow_empty_eof) { - done_ = true; - return std::nullopt; + if (avail() == 0) { + if (refill_for_record(refill_step, false, false) == 0) { + if (record_too_large_) { + return fail("JSON record exceeds maximum allowed size."); } return eof_or_io_error( "Could not parse document: unexpected end of data"); @@ -299,24 +856,61 @@ class StreamReader { continue; } + const char* ptr = data_ptr() + pos_; + const size_t cur_avail = avail(); + size_t slice_len = std::min(cur_avail, window); + bool hit_size_cap = false; + + if (max_record_bytes_ > 0) { + const size_t allowed_slice = safe_inc(max_record_bytes_); + if (slice_len > allowed_slice) { + slice_len = allowed_slice; + hit_size_cap = true; + } else if (slice_len == allowed_slice && + !(slice_len == cur_avail && eof_)) { + hit_size_cap = true; + } + } + yyjson_read_err err{}; - yyjson_doc* doc = yyjson_read_opts(buf_.data() + pos_, avail, + yyjson_doc* doc = yyjson_read_opts(const_cast(ptr), slice_len, effective_flag, nullptr, &err); if (doc) { const size_t read_size = yyjson_doc_get_read_size(doc); yyjson_val* root = yyjson_doc_get_root(doc); const bool is_self_delimiting = yyjson_is_ctn(root) || yyjson_is_str(root); - // Refill before committing bare primitives (e.g. `12` + `3`) at the - // exact buffer boundary when more bytes may still arrive. - if (!is_self_delimiting && pos_ + read_size == buf_.size() && !eof_) { + + const bool more_bytes_possible = (slice_len < cur_avail) || !eof_; + if (!is_self_delimiting && read_size == slice_len && + more_bytes_possible) { yyjson_doc_free(doc); - if (!refill() && io_error_) { - return fail("I/O error while reading JSON stream."); + if (hit_size_cap || + (max_record_bytes_ > 0 && read_size > max_record_bytes_)) { + return fail("JSON record exceeds maximum allowed size."); + } + if (slice_len < cur_avail) { + window = safe_double(window); + } else { + refill_step = safe_double(refill_step); + window = std::max(safe_double(slice_len), window); + if (refill_for_record(refill_step, false, false) == 0) { + if (record_too_large_) { + return fail("JSON record exceeds maximum allowed size."); + } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } + } } continue; } + if (max_record_bytes_ > 0 && read_size > max_record_bytes_) { + yyjson_doc_free(doc); + return fail("JSON record exceeds maximum allowed size."); + } + pos_ += read_size; const auto r = Reader(); auto res = @@ -329,56 +923,85 @@ class StreamReader { const bool maybe_truncated = (err.code == YYJSON_READ_ERROR_UNEXPECTED_END || err.code == YYJSON_READ_ERROR_EMPTY_CONTENT); - if (maybe_truncated && !eof_) { - if (refill()) { + if (maybe_truncated) { + if (hit_size_cap || + (max_record_bytes_ > 0 && slice_len >= safe_inc(max_record_bytes_))) { + return fail("JSON record exceeds maximum allowed size."); + } + if (slice_len < cur_avail) { + window = safe_double(window); continue; } - if (io_error_) { - return fail("I/O error while reading JSON stream."); + if (!eof_) { + refill_step = safe_double(refill_step); + window = std::max(safe_double(slice_len), window); + if (refill_for_record(refill_step, false, false) > 0) { + continue; + } + if (record_too_large_) { + return fail("JSON record exceeds maximum allowed size."); + } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } } } done_ = true; - if (_allow_empty_eof && err.code == YYJSON_READ_ERROR_EMPTY_CONTENT) { - return std::nullopt; - } return error("Could not parse document: " + std::string(err.msg ? err.msg : "unknown error")); } } std::optional next_delimited(const bool _skip_rs) { - if (!skip_ws(_skip_rs)) { + const auto skipped = skip_ws(_skip_rs); + if (skipped == SkipResult::eof) { done_ = true; - if (io_error_) { - return error("I/O error while reading JSON stream."); - } return std::nullopt; } - return parse_next_value(true); + if (skipped == SkipResult::io_error) { + return fail("I/O error while reading JSON stream."); + } + if (skipped == SkipResult::unclosed_comment) { + return fail("Unclosed multi-line comment in JSON stream."); + } + return parse_delimited_value(_skip_rs); } std::optional finish_array() { ++pos_; // consume ']' array_state_ = ArrayState::closed; done_ = true; - if (skip_ws(false)) { + const auto skipped = skip_ws(false); + if (skipped == SkipResult::found) { return error( "Unexpected trailing content after closing ']' of JSON array."); } - if (io_error_) { + if (skipped == SkipResult::io_error) { return error("I/O error while reading JSON stream."); } + if (skipped == SkipResult::unclosed_comment) { + return error("Unclosed multi-line comment in JSON stream."); + } return std::nullopt; } std::optional next_array_element() { + auto handle_skip_error = [&](const SkipResult _sr, + const char* _eof_msg) -> std::optional { + if (_sr == SkipResult::unclosed_comment) { + return fail("Unclosed multi-line comment in JSON stream."); + } + return eof_or_io_error(_eof_msg); + }; + if (array_state_ == ArrayState::before_open) { - if (!skip_ws(false)) { - return eof_or_io_error( - "Expected '[' at start of JSON array, got end of input."); + const auto skipped = skip_ws(false); + if (skipped != SkipResult::found) { + return handle_skip_error( + skipped, "Expected '[' at start of JSON array, got end of input."); } - if (buf_[pos_] != '[') { + if (data_ptr()[pos_] != '[') { return fail("Expected '[' at start of JSON array."); } ++pos_; @@ -386,14 +1009,16 @@ class StreamReader { } if (array_state_ == ArrayState::expect_first) { - if (!skip_ws(false)) { - return eof_or_io_error( + const auto skipped = skip_ws(false); + if (skipped != SkipResult::found) { + return handle_skip_error( + skipped, "Unexpected end of input in JSON array: expected ']' or value."); } - if (buf_[pos_] == ']') { + if (data_ptr()[pos_] == ']') { return finish_array(); } - auto res = parse_next_value(false); + auto res = parse_array_value(); if (!done_) { array_state_ = ArrayState::expect_sep_end; } @@ -401,28 +1026,31 @@ class StreamReader { } if (array_state_ == ArrayState::expect_sep_end) { - if (!skip_ws(false)) { - return eof_or_io_error( + const auto skipped = skip_ws(false); + if (skipped != SkipResult::found) { + return handle_skip_error( + skipped, "Unexpected end of input in JSON array: expected ',' or ']'."); } - if (buf_[pos_] == ']') { + if (data_ptr()[pos_] == ']') { return finish_array(); } - if (buf_[pos_] != ',') { + if (data_ptr()[pos_] != ',') { return fail("Expected ',' or ']' in JSON array."); } ++pos_; // consume ',' - if (!skip_ws(false)) { - return eof_or_io_error( - "Unexpected end of input in JSON array after ','."); + const auto after_comma = skip_ws(false); + if (after_comma != SkipResult::found) { + return handle_skip_error( + after_comma, "Unexpected end of input in JSON array after ','."); } - if (buf_[pos_] == ']') { + if (data_ptr()[pos_] == ']') { if (flag_ & YYJSON_READ_ALLOW_TRAILING_COMMAS) { return finish_array(); } return fail("Trailing comma is not allowed in JSON array."); } - return parse_next_value(false); + return parse_array_value(); } done_ = true; @@ -433,10 +1061,14 @@ class StreamReader { StreamFormat format_; yyjson_read_flag flag_; size_t chunk_size_; + size_t max_record_bytes_; + std::string_view input_; std::string buf_; size_t pos_ = 0; bool eof_ = false; bool io_error_ = false; + bool record_too_large_ = false; + bool bom_checked_ = false; bool done_ = false; bool invalid_flag_ = false; ArrayState array_state_ = ArrayState::before_open; diff --git a/tests/json/test_stream.cpp b/tests/json/test_stream.cpp index 17c577516..fd392fd2f 100644 --- a/tests/json/test_stream.cpp +++ b/tests/json/test_stream.cpp @@ -1,11 +1,15 @@ #include +#include +#include #include +#include #include #include #include #include #include +#include #include #include @@ -31,8 +35,41 @@ struct MoveOnlyRow { static_assert(std::input_iterator::Iterator>); static_assert(std::ranges::input_range>); +static_assert( + std::same_as&>().end()), + std::default_sentinel_t>); static_assert( std::input_iterator::Iterator>); +static_assert(std::ranges::input_range>); + +// Simulated live pipe streambuf: yields chunks one at a time and tracks how +// many underflow() calls have occurred so tests can assert non-blocking reads. +class ChunkedPipeBuf : public std::streambuf { + public: + void push_chunk(std::string _chunk) { chunks_.push_back(std::move(_chunk)); } + + size_t underflow_count() const noexcept { return underflows_; } + + protected: + int_type underflow() override { + if (gptr() < egptr()) { + return traits_type::to_int_type(*gptr()); + } + if (chunks_.empty()) { + return traits_type::eof(); + } + ++underflows_; + current_ = std::move(chunks_.front()); + chunks_.pop_front(); + setg(current_.data(), current_.data(), current_.data() + current_.size()); + return traits_type::to_int_type(*gptr()); + } + + private: + std::deque chunks_; + std::string current_; + size_t underflows_ = 0; +}; template std::vector collect_ok(rfl::json::StreamReader& _reader) { @@ -59,8 +96,11 @@ TEST(json, test_stream_ndjson_roundtrip) { std::stringstream ss; { rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::ndjson); - for (const auto& row : expected) writer.write(row); - writer.finish(); + for (const auto& row : expected) { + ASSERT_TRUE(writer.write(row).has_value()); + } + ASSERT_TRUE(writer.flush().has_value()); + ASSERT_TRUE(writer.finish().has_value()); } const std::string payload = ss.str(); @@ -92,7 +132,9 @@ TEST(json, test_stream_json_seq_roundtrip_and_consecutive_rs) { std::stringstream ss; { rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::json_seq); - for (const auto& row : expected) writer.write(row); + for (const auto& row : expected) { + ASSERT_TRUE(writer.write(row).has_value()); + } } ASSERT_FALSE(ss.str().empty()); EXPECT_EQ(ss.str().front(), '\x1e'); @@ -116,10 +158,13 @@ TEST(json, test_stream_json_array_roundtrip_and_finish) { std::stringstream ss; { rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::json_array); - for (const auto& row : expected) writer.write(row); - writer.finish(); - writer.finish(); // idempotent - EXPECT_THROW(writer.write(expected.front()), std::runtime_error); + for (const auto& row : expected) { + ASSERT_TRUE(writer.write(row).has_value()); + } + ASSERT_TRUE(writer.finish().has_value()); + ASSERT_TRUE(writer.finish().has_value()); // idempotent + const auto after_finish = writer.write(expected.front()); + EXPECT_FALSE(after_finish.has_value()); } const std::string payload = ss.str(); @@ -136,7 +181,10 @@ TEST(json, test_stream_json_array_roundtrip_and_finish) { // 0 records + destructor auto-finish emits "[]" std::stringstream empty_ss; - { rfl::json::StreamWriter writer(empty_ss, rfl::json::StreamFormat::json_array); } + { + rfl::json::StreamWriter writer(empty_ss, + rfl::json::StreamFormat::json_array); + } EXPECT_EQ(empty_ss.str(), "[]"); } @@ -173,18 +221,98 @@ TEST(json, test_stream_empty_inputs) { TEST(json, test_stream_multiline_and_pretty_records) { const auto expected = sample_rows(); - for (const auto fmt : - {rfl::json::StreamFormat::ndjson, rfl::json::StreamFormat::json_seq, - rfl::json::StreamFormat::json_array}) { + + // StreamWriter allows pretty printing for json_array + { std::stringstream ss; { - rfl::json::StreamWriter writer(ss, fmt, rfl::json::pretty); - for (const auto& row : expected) writer.write(row); + rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::json_array, + rfl::json::pretty); + for (const auto& row : expected) { + ASSERT_TRUE(writer.write(row).has_value()); + } } std::istringstream in(ss.str()); - rfl::json::StreamReader reader(in, fmt, 0, 13); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::json_array, + 0, 13); EXPECT_EQ(collect_ok(reader), expected); } + + // StreamReader still supports reading multi-line / pretty-printed ndjson and + // json_seq records (both istream and string_view) + { + std::string ndjson_pretty; + std::string seq_pretty; + for (const auto& row : expected) { + const auto pretty_rec = rfl::json::write(row, rfl::json::pretty); + ndjson_pretty += pretty_rec + "\n"; + seq_pretty += '\x1e'; + seq_pretty += pretty_rec + "\n"; + } + + std::istringstream in_nd(ndjson_pretty); + rfl::json::StreamReader r_nd_in(in_nd, rfl::json::StreamFormat::ndjson, + 0, 13); + EXPECT_EQ(collect_ok(r_nd_in), expected); + + rfl::json::StreamReader r_nd_sv(std::string_view{ndjson_pretty}, + rfl::json::StreamFormat::ndjson); + EXPECT_EQ(collect_ok(r_nd_sv), expected); + + std::istringstream in_seq(seq_pretty); + rfl::json::StreamReader r_seq_in( + in_seq, rfl::json::StreamFormat::json_seq, 0, 13); + EXPECT_EQ(collect_ok(r_seq_in), expected); + + rfl::json::StreamReader r_seq_sv(std::string_view{seq_pretty}, + rfl::json::StreamFormat::json_seq); + EXPECT_EQ(collect_ok(r_seq_sv), expected); + } +} + +TEST(json, test_stream_writer_errors_and_flags) { + const Row sample{1, "Alice", 9.5}; + + // Pretty / newline-at-end flags rejected for ndjson and json_seq + for (const auto fmt : + {rfl::json::StreamFormat::ndjson, rfl::json::StreamFormat::json_seq}) { + for (const yyjson_write_flag bad_flag : + {YYJSON_WRITE_PRETTY, YYJSON_WRITE_PRETTY_TWO_SPACES, + YYJSON_WRITE_NEWLINE_AT_END}) { + std::stringstream ss; + rfl::json::StreamWriter writer(ss, fmt, bad_flag); + const auto res = writer.write(sample); + EXPECT_FALSE(res.has_value()); + EXPECT_TRUE(ss.str().empty()); + } + } + + // Bad / failbit ostream returns rfl::Error from write(), flush(), finish() + { + std::stringstream ss; + ss.setstate(std::ios::badbit); + rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::ndjson); + EXPECT_FALSE(writer.write(sample).has_value()); + EXPECT_FALSE(writer.flush().has_value()); + EXPECT_FALSE(writer.finish().has_value()); + } + { + std::stringstream ss; + ss.setstate(std::ios::failbit); + rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::json_array); + EXPECT_FALSE(writer.write(sample).has_value()); + EXPECT_FALSE(writer.finish().has_value()); + } + + // Serialization failure (e.g. NaN without ALLOW_INF_AND_NAN) returns Error + { + std::stringstream ss; + rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::ndjson); + const Row nan_row{1, "NaN", std::numeric_limits::quiet_NaN()}; + const auto res = writer.write(nan_row); + EXPECT_FALSE(res.has_value()); + EXPECT_TRUE(ss.str().empty()); + } } TEST(json, test_stream_tiny_chunks_primitives_and_objects) { @@ -199,7 +327,9 @@ TEST(json, test_stream_tiny_chunks_primitives_and_objects) { std::stringstream str_ss; { rfl::json::StreamWriter writer(str_ss, rfl::json::StreamFormat::ndjson); - for (const auto& s : expected_strs) writer.write(s); + for (const auto& s : expected_strs) { + ASSERT_TRUE(writer.write(s).has_value()); + } } const std::vector expected_rows = { @@ -209,7 +339,9 @@ TEST(json, test_stream_tiny_chunks_primitives_and_objects) { std::stringstream obj_ss; { rfl::json::StreamWriter writer(obj_ss, rfl::json::StreamFormat::json_array); - for (const auto& r : expected_rows) writer.write(r); + for (const auto& r : expected_rows) { + ASSERT_TRUE(writer.write(r).has_value()); + } } for (const size_t chunk : {size_t{1}, size_t{3}, size_t{7}, size_t{13}}) { @@ -240,12 +372,75 @@ TEST(json, test_stream_tiny_chunks_primitives_and_objects) { } } +TEST(json, test_stream_live_pipe_non_blocking) { + // NDJSON yields record 1 immediately without pulling chunk 2 + { + ChunkedPipeBuf pipe; + pipe.push_chunk(R"({"id":1,"name":"live1","score":1.0})" "\n"); + pipe.push_chunk(R"({"id":2,"name":"live2","score":2.0})" "\n"); + std::istream in(&pipe); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, (Row{1, "live1", 1.0})); + EXPECT_EQ(pipe.underflow_count(), 1u); + + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value() && r2->has_value()); + EXPECT_EQ(**r2, (Row{2, "live2", 2.0})); + EXPECT_EQ(pipe.underflow_count(), 2u); + } + + // json_seq yields record 1 immediately without pulling chunk 2 + { + ChunkedPipeBuf pipe; + pipe.push_chunk("\x1e" R"({"id":1,"name":"seq1","score":1.0})" "\n"); + pipe.push_chunk("\x1e" R"({"id":2,"name":"seq2","score":2.0})" "\n"); + std::istream in(&pipe); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::json_seq); + + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, (Row{1, "seq1", 1.0})); + EXPECT_EQ(pipe.underflow_count(), 1u); + + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value() && r2->has_value()); + EXPECT_EQ(**r2, (Row{2, "seq2", 2.0})); + EXPECT_EQ(pipe.underflow_count(), 2u); + } + + // json_array yields element 1 immediately without pulling chunk 2 + { + ChunkedPipeBuf pipe; + pipe.push_chunk(R"([{"id":1,"name":"arr1","score":1.0},)"); + pipe.push_chunk(R"({"id":2,"name":"arr2","score":2.0}])"); + std::istream in(&pipe); + rfl::json::StreamReader reader(in, + rfl::json::StreamFormat::json_array); + + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, (Row{1, "arr1", 1.0})); + EXPECT_EQ(pipe.underflow_count(), 1u); + + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value() && r2->has_value()); + EXPECT_EQ(**r2, (Row{2, "arr2", 2.0})); + EXPECT_EQ(pipe.underflow_count(), 2u); + EXPECT_FALSE(reader.next().has_value()); + } +} + TEST(json, test_stream_processors_and_move_only) { const std::vector expected = {{1, "Ada"}, {2, "Grace"}}; std::stringstream ss; { rfl::json::StreamWriter writer(ss); - for (const auto& r : expected) writer.write(r); + for (const auto& r : expected) { + ASSERT_TRUE(writer.write(r).has_value()); + } } EXPECT_NE(ss.str().find("\"userId\""), std::string::npos); EXPECT_NE(ss.str().find("\"firstName\""), std::string::npos); @@ -286,6 +481,337 @@ TEST(json, test_stream_processors_and_move_only) { EXPECT_EQ(*moved[1].label, "second"); } +TEST(json, test_stream_syntax_error_recovery) { + // NDJSON recovers after malformed line and reads subsequent valid records + const std::string bad_ndjson = + R"({"id":1,"name":"first","score":1.0})" "\n" + "{not valid json}\n" + R"({"id":2,"name":"second","score":2.0})" "\n" + R"({"id":3,"name":"trunc)" "\n" + R"({"id":4,"name":"fourth","score":4.0})" "\n"; + + for (const bool use_stream : {false, true}) { + std::istringstream in(bad_ndjson); + auto reader = + use_stream + ? rfl::json::StreamReader(in, rfl::json::StreamFormat::ndjson, + 0, 11) + : rfl::json::StreamReader(std::string_view{bad_ndjson}, + rfl::json::StreamFormat::ndjson); + + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, (Row{1, "first", 1.0})); + + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value()); + EXPECT_FALSE(r2->has_value()); + + const auto r3 = reader.next(); + ASSERT_TRUE(r3.has_value() && r3->has_value()); + EXPECT_EQ(**r3, (Row{2, "second", 2.0})); + + const auto r4 = reader.next(); + ASSERT_TRUE(r4.has_value()); + EXPECT_FALSE(r4->has_value()); + + const auto r5 = reader.next(); + ASSERT_TRUE(r5.has_value() && r5->has_value()); + EXPECT_EQ(**r5, (Row{4, "fourth", 4.0})); + + EXPECT_FALSE(reader.next().has_value()); + } + + // RFC 7464 json_seq resyncs to next \x1e across malformed/multi-line garbage + const std::string bad_seq = + "\x1e" R"({"id":1,"name":"ok1","score":1.0})" "\n" + "\x1e{bad\nstill bad}\n" + "\x1e" R"({"id":2,"name":"trunc)" + "\x1e" R"({"id":3,"name":"ok3","score":3.0})" "\n"; + + for (const bool use_stream : {false, true}) { + std::istringstream in(bad_seq); + auto reader = + use_stream + ? rfl::json::StreamReader( + in, rfl::json::StreamFormat::json_seq, 0, 11) + : rfl::json::StreamReader(std::string_view{bad_seq}, + rfl::json::StreamFormat::json_seq); + + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, (Row{1, "ok1", 1.0})); + + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value()); + EXPECT_FALSE(r2->has_value()); + + const auto r3 = reader.next(); + ASSERT_TRUE(r3.has_value()); + EXPECT_FALSE(r3->has_value()); + + const auto r4 = reader.next(); + ASSERT_TRUE(r4.has_value() && r4->has_value()); + EXPECT_EQ(**r4, (Row{3, "ok3", 3.0})); + + EXPECT_FALSE(reader.next().has_value()); + } +} + +TEST(json, test_stream_max_record_bytes) { + const std::string big_ndjson = + R"({"id":1,"name":"ok","score":1.0})" "\n" + "{\"id\":2,\"name\":\"" + + std::string(200, 'x') + "\",\"score\":2.0}\n"; + + // Small cap rejects oversized record in ndjson (both string_view & istream) + { + rfl::json::StreamReader reader(std::string_view{big_ndjson}, + rfl::json::StreamFormat::ndjson, 0, 64); + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, (Row{1, "ok", 1.0})); + + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value()); + EXPECT_FALSE(r2->has_value()); + EXPECT_FALSE(reader.next().has_value()); + } + { + std::istringstream in(big_ndjson); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson, 0, + 16, 64); + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value()); + EXPECT_FALSE(r2->has_value()); + EXPECT_FALSE(reader.next().has_value()); + } + + // Cap enforced in json_array as well + const std::string big_array = + R"([{"id":1,"name":"ok","score":1.0},{"id":2,"name":")" + + std::string(200, 'y') + R"(","score":2.0}])"; + { + std::istringstream in(big_array); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::json_array, + 0, 16, 64); + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value()); + EXPECT_FALSE(r2->has_value()); + EXPECT_FALSE(reader.next().has_value()); + } + + // 0 means unlimited + { + std::istringstream in(big_ndjson); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson, 0, + 16, 0); + const auto rows = collect_ok(reader); + ASSERT_EQ(rows.size(), 2u); + EXPECT_EQ(rows[1].name.size(), 200u); + } +} + +TEST(json, test_stream_bom_and_comments) { + const std::string bom_and_comments_array = + "\xEF\xBB\xBF" + "/* leading comment */\n" + "[ // after open\n" + " {\"id\":1,\"name\":\"A\",\"score\":1.0} /* mid */,\n" + " // before second\n" + " {\"id\":2,\"name\":\"B\",\"score\":2.0}\n" + "] /* trailing */"; + + const std::vector expected{{1, "A", 1.0}, {2, "B", 2.0}}; + + // Works with ALLOW_BOM | ALLOW_COMMENTS (including tiny chunk_size = 1) + { + rfl::json::StreamReader sv_reader( + std::string_view{bom_and_comments_array}, + rfl::json::StreamFormat::json_array, + YYJSON_READ_ALLOW_BOM | YYJSON_READ_ALLOW_COMMENTS); + EXPECT_EQ(collect_ok(sv_reader), expected); + + std::istringstream in(bom_and_comments_array); + rfl::json::StreamReader in_reader( + in, rfl::json::StreamFormat::json_array, + YYJSON_READ_ALLOW_BOM | YYJSON_READ_ALLOW_COMMENTS, 1); + EXPECT_EQ(collect_ok(in_reader), expected); + } + + // Rejected without ALLOW_BOM + { + rfl::json::StreamReader reader( + std::string_view{bom_and_comments_array}, + rfl::json::StreamFormat::json_array, YYJSON_READ_ALLOW_COMMENTS); + const auto res = reader.next(); + ASSERT_TRUE(res.has_value()); + EXPECT_FALSE(res->has_value()); + } + + // Unclosed multi-line comment returns error + { + const std::string unclosed = "[1 /* unclosed"; + rfl::json::StreamReader reader(std::string_view{unclosed}, + rfl::json::StreamFormat::json_array, + YYJSON_READ_ALLOW_COMMENTS); + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, 1); + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value()); + EXPECT_FALSE(r2->has_value()); + } + + // BOM + comments also work in ndjson + { + const std::string bom_ndjson = + "\xEF\xBB\xBF" + "// header\n" + "{\"id\":1,\"name\":\"A\",\"score\":1.0}\n" + "/* between */\n" + "{\"id\":2,\"name\":\"B\",\"score\":2.0}\n"; + std::istringstream in(bom_ndjson); + rfl::json::StreamReader reader( + in, rfl::json::StreamFormat::ndjson, + YYJSON_READ_ALLOW_BOM | YYJSON_READ_ALLOW_COMMENTS, 1); + EXPECT_EQ(collect_ok(reader), expected); + } +} + +TEST(json, test_stream_linear_performance_sanity) { + constexpr int kCount = 10000; + std::stringstream nd_ss; + std::stringstream seq_ss; + std::stringstream arr_ss; + { + rfl::json::StreamWriter nd_w(nd_ss, rfl::json::StreamFormat::ndjson); + rfl::json::StreamWriter seq_w(seq_ss, rfl::json::StreamFormat::json_seq); + rfl::json::StreamWriter arr_w(arr_ss, rfl::json::StreamFormat::json_array); + for (int i = 0; i < kCount; ++i) { + const Row row{i, "record_payload", static_cast(i) * 0.5}; + ASSERT_TRUE(nd_w.write(row).has_value()); + ASSERT_TRUE(seq_w.write(row).has_value()); + ASSERT_TRUE(arr_w.write(row).has_value()); + } + } + + const std::string nd_payload = nd_ss.str(); + const std::string seq_payload = seq_ss.str(); + const std::string arr_payload = arr_ss.str(); + + auto measure_ms = [](auto&& _fn) { + const auto t0 = std::chrono::steady_clock::now(); + _fn(); + const auto t1 = std::chrono::steady_clock::now(); + return std::chrono::duration_cast(t1 - t0) + .count(); + }; + + // O(N^2) yyjson copy would take many seconds on 10,000 records (~500 KB); + // windowed O(N) parsing completes well within budget. + constexpr long long kBudgetMs = 2000; + + { + int count = 0; + const auto ms = measure_ms([&] { + rfl::json::StreamReader reader(std::string_view{nd_payload}, + rfl::json::StreamFormat::ndjson); + for (auto&& res : reader) { + ASSERT_TRUE(res.has_value()); + ++count; + } + }); + EXPECT_EQ(count, kCount); + EXPECT_LT(ms, kBudgetMs) << "ndjson string_view took " << ms << "ms"; + } + + { + int count = 0; + const auto ms = measure_ms([&] { + std::istringstream in(nd_payload); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + for (auto&& res : reader) { + ASSERT_TRUE(res.has_value()); + ++count; + } + }); + EXPECT_EQ(count, kCount); + EXPECT_LT(ms, kBudgetMs) << "ndjson istream took " << ms << "ms"; + } + + { + int count = 0; + const auto ms = measure_ms([&] { + rfl::json::StreamReader reader(std::string_view{seq_payload}, + rfl::json::StreamFormat::json_seq); + for (auto&& res : reader) { + ASSERT_TRUE(res.has_value()); + ++count; + } + }); + EXPECT_EQ(count, kCount); + EXPECT_LT(ms, kBudgetMs) << "json_seq string_view took " << ms << "ms"; + } + + { + int count = 0; + const auto ms = measure_ms([&] { + rfl::json::StreamReader reader(std::string_view{arr_payload}, + rfl::json::StreamFormat::json_array); + for (auto&& res : reader) { + ASSERT_TRUE(res.has_value()); + ++count; + } + }); + EXPECT_EQ(count, kCount); + EXPECT_LT(ms, kBudgetMs) << "json_array string_view took " << ms << "ms"; + } + + { + int count = 0; + const auto ms = measure_ms([&] { + std::istringstream in(arr_payload); + rfl::json::StreamReader reader(in, + rfl::json::StreamFormat::json_array); + for (auto&& res : reader) { + ASSERT_TRUE(res.has_value()); + ++count; + } + }); + EXPECT_EQ(count, kCount); + EXPECT_LT(ms, kBudgetMs) << "json_array istream took " << ms << "ms"; + } + + // B2: Large single record (256 KiB) with tiny initial chunk_size (16 bytes) + // doubles refill step so parsing is O(R), not O(R^2 / chunk_size). + { + const Row big_row{42, std::string(256 * 1024, 'z'), 3.14}; + std::stringstream big_ss; + { + rfl::json::StreamWriter w(big_ss, rfl::json::StreamFormat::json_array); + ASSERT_TRUE(w.write(big_row).has_value()); + } + const std::string big_payload = big_ss.str(); + const auto ms = measure_ms([&] { + std::istringstream in(big_payload); + rfl::json::StreamReader reader(in, + rfl::json::StreamFormat::json_array, + 0, 16); + const auto res = reader.next(); + ASSERT_TRUE(res.has_value() && res->has_value()); + EXPECT_EQ(**res, big_row); + EXPECT_FALSE(reader.next().has_value()); + }); + EXPECT_LT(ms, kBudgetMs) << "large record doubling took " << ms << "ms"; + } +} + TEST(json, test_stream_error_handling) { // YYJSON_READ_INSITU rejected { From f7f5d1effc9d1a6d21114db447bdcf6438da2627 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 10:30:26 +0100 Subject: [PATCH 3/4] Fix final JSON streaming blockers, extract engine to stream.cpp, add ASAN tests --- README.md | 2 + docs/content/supported_formats/json.md | 2 +- include/rfl/json/stream.hpp | 954 ++++-------------------- src/reflectcpp_json.cpp | 1 + src/rfl/json/stream.cpp | 980 +++++++++++++++++++++++++ tests/json/test_stream.cpp | 283 ++++++- 6 files changed, 1395 insertions(+), 827 deletions(-) create mode 100644 src/rfl/json/stream.cpp diff --git a/README.md b/README.md index 9cfdfa223..4aba9c64d 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,8 @@ The resulting JSON string looks like this: {"firstName":"Homer","lastName":"Simpson","age":45} ``` +For large datasets or live streams, `rfl::json::StreamReader` and `rfl::json::StreamWriter` also support record-level JSON streaming (NDJSON, RFC 7464 JSON Text Sequences, and JSON arrays) — see the [JSON documentation](https://munich-data-engineering.github.io/reflect-cpp/supported_formats/json/#record-level-streaming). + Or you can use another format, such as YAML. ```cpp diff --git a/docs/content/supported_formats/json.md b/docs/content/supported_formats/json.md index b0aada33f..abdd2a223 100644 --- a/docs/content/supported_formats/json.md +++ b/docs/content/supported_formats/json.md @@ -92,8 +92,8 @@ rfl::json::StreamWriter writer(my_ostream, rfl::json::StreamFormat::ndjson); for (const auto& person : people) { writer.write(person).value(); } -writer.flush().value(); writer.finish().value(); +writer.flush().value(); // Reading records incrementally (C++20 input_range or next()) rfl::json::StreamReader reader(my_istream, rfl::json::StreamFormat::ndjson); diff --git a/include/rfl/json/stream.hpp b/include/rfl/json/stream.hpp index f24b92929..65d077747 100644 --- a/include/rfl/json/stream.hpp +++ b/include/rfl/json/stream.hpp @@ -7,14 +7,11 @@ #include "../thirdparty/yyjson.h" #endif -#include #include #include -#include #include #include #include -#include #include #include #include @@ -25,12 +22,12 @@ #include "../Processors.hpp" #include "../Result.hpp" +#include "../common.hpp" #include "../internal/wrap_in_rfl_array_t.hpp" #include "../parsing/Parent.hpp" #include "Parser.hpp" #include "Reader.hpp" #include "Writer.hpp" -#include "write.hpp" namespace rfl { namespace json { @@ -59,9 +56,11 @@ class StreamWriter { format_(_other.format_), flag_(_other.flag_), started_(_other.started_), - finished_(_other.finished_) { + finished_(_other.finished_), + finish_error_(std::move(_other.finish_error_)) { _other.stream_ = nullptr; _other.finished_ = true; + _other.finish_error_.reset(); } StreamWriter& operator=(StreamWriter&&) = delete; @@ -86,9 +85,12 @@ class StreamWriter { "Pretty-printing and trailing newline flags are not allowed for " "NDJSON or JSON Text Sequences."); } - if (!stream_ || !stream_->good()) { + if (!stream_ || stream_->fail() || stream_->bad()) { return error("Output stream is not in a good state."); } + if (stream_->eof()) { + stream_->clear(stream_->rdstate() & ~std::ios_base::eofbit); + } try { using T = std::remove_cvref_t; using ParentType = parsing::Parent; @@ -137,6 +139,9 @@ class StreamWriter { if (stream_->fail() || stream_->bad()) { return error("Output stream is not in a good state."); } + if (stream_->eof()) { + stream_->clear(stream_->rdstate() & ~std::ios_base::eofbit); + } try { stream_->flush(); if (stream_->fail() || stream_->bad()) { @@ -149,14 +154,26 @@ class StreamWriter { return Nothing{}; } - /// Finishes the stream (emits `[]` or `]` for `json_array`). Idempotent. + /// Finishes the stream (emits `[]` or `]` for `json_array`). Idempotent; + /// if finishing failed, subsequent retries return the error. Result finish() { if (finished_) { + if (finish_error_.has_value()) { + return error(*finish_error_); + } return Nothing{}; } finished_ = true; if (!stream_) { - return error("StreamWriter has no output stream."); + finish_error_ = "StreamWriter has no output stream."; + return error(*finish_error_); + } + if (stream_->fail() || stream_->bad()) { + finish_error_ = "I/O error while finishing JSON stream."; + return error(*finish_error_); + } + if (stream_->eof()) { + stream_->clear(stream_->rdstate() & ~std::ios_base::eofbit); } try { if (format_ == StreamFormat::json_array) { @@ -167,11 +184,13 @@ class StreamWriter { } } if (stream_->fail() || stream_->bad()) { - return error("I/O error while finishing JSON stream."); + finish_error_ = "I/O error while finishing JSON stream."; + return error(*finish_error_); } } catch (const std::exception& _e) { - return error(std::string("I/O error while finishing JSON stream: ") + - _e.what()); + finish_error_ = + std::string("I/O error while finishing JSON stream: ") + _e.what(); + return error(*finish_error_); } return Nothing{}; } @@ -182,8 +201,97 @@ class StreamWriter { yyjson_write_flag flag_; bool started_ = false; bool finished_ = false; + std::optional finish_error_; +}; + +namespace detail { + +struct YYJsonDocDeleter { + void operator()(yyjson_doc* _doc) const noexcept { yyjson_doc_free(_doc); } +}; + +using YYJsonDocPtr = std::unique_ptr; + +/// Non-template framing, buffering, and incremental JSON value scanning engine +/// shared by all StreamReader instantiations. +class RFL_API StreamReaderEngine { + public: + StreamReaderEngine(std::istream& _stream, StreamFormat _format, + yyjson_read_flag _flag, size_t _chunk_size, + size_t _max_record_bytes); + + StreamReaderEngine(std::string_view _input, StreamFormat _format, + yyjson_read_flag _flag, size_t _max_record_bytes); + + StreamReaderEngine(const StreamReaderEngine&) = delete; + StreamReaderEngine& operator=(const StreamReaderEngine&) = delete; + StreamReaderEngine(StreamReaderEngine&&) = default; + StreamReaderEngine& operator=(StreamReaderEngine&&) = default; + ~StreamReaderEngine() = default; + + std::optional> next_doc(); + + private: + enum class ArrayState { before_open, expect_first, expect_sep_end, closed }; + enum class SkipResult { found, eof, io_error, unclosed_comment }; + enum class CommentMode { none, slash, line, block, block_star }; + enum class ScanOutcome { + complete, + hard_boundary, + syntax_break, + too_large, + io_error, + eof_truncated, + }; + + struct ScanResult { + ScanOutcome outcome; + size_t slice_len = 0; + }; + + const char* data_ptr() const noexcept; + size_t data_size() const noexcept; + size_t avail() const noexcept; + + std::optional> fail(const std::string& _msg); + std::optional> eof_or_io_error(const char* _eof_msg); + + void compact_buffer(); + size_t refill_raw(size_t _requested, bool _line_mode, bool _stop_at_rs); + size_t refill_for_record(size_t _requested, bool _line_mode, + bool _stop_at_rs); + bool skip_bom_if_needed(); + SkipResult skip_ws(bool _skip_rs); + void advance_past_newline(); + void resync_to_rs(); + + ScanResult scan_value(bool _line_mode, bool _is_seq, bool _check_first_nl, + std::string* _first_nl_err); + + std::optional> parse_delimited_value(bool _is_seq); + std::optional> parse_array_value(); + std::optional> next_delimited(bool _skip_rs); + std::optional> finish_array(); + std::optional> next_array_element(); + + std::istream* stream_; + StreamFormat format_; + yyjson_read_flag flag_; + size_t chunk_size_; + size_t max_record_bytes_; + std::string_view input_; + std::string buf_; + size_t pos_ = 0; + bool eof_ = false; + bool io_error_ = false; + bool bom_checked_ = false; + bool done_ = false; + bool invalid_flag_ = false; + ArrayState array_state_ = ArrayState::before_open; }; +} // namespace detail + /// Record-level streaming JSON reader. template class StreamReader { @@ -231,26 +339,14 @@ class StreamReader { std::istream& _stream, const StreamFormat _format = StreamFormat::ndjson, const yyjson_read_flag _flag = 0, const size_t _chunk_size = 65536, const size_t _max_record_bytes = kDefaultMaxRecordBytes) - : stream_(&_stream), - format_(_format), - flag_(_flag), - chunk_size_(_chunk_size > 0 ? _chunk_size : 1), - max_record_bytes_(_max_record_bytes), - invalid_flag_((_flag & YYJSON_READ_INSITU) != 0) {} + : engine_(_stream, _format, _flag, _chunk_size, _max_record_bytes) {} explicit StreamReader( const std::string_view _input, const StreamFormat _format = StreamFormat::ndjson, const yyjson_read_flag _flag = 0, const size_t _max_record_bytes = kDefaultMaxRecordBytes) - : stream_(nullptr), - format_(_format), - flag_(_flag), - chunk_size_(0), - max_record_bytes_(_max_record_bytes), - input_(_input), - eof_(true), - invalid_flag_((_flag & YYJSON_READ_INSITU) != 0) {} + : engine_(_input, _format, _flag, _max_record_bytes) {} StreamReader(const StreamReader&) = delete; StreamReader& operator=(const StreamReader&) = delete; @@ -259,22 +355,16 @@ class StreamReader { /// Reads the next record, or returns `std::nullopt` at clean EOF. std::optional next() { - if (done_) { + auto doc_opt = engine_.next_doc(); + if (!doc_opt.has_value()) { return std::nullopt; } - if (invalid_flag_) { - return fail("YYJSON_READ_INSITU is not supported"); - } - switch (format_) { - case StreamFormat::ndjson: - return next_delimited(false); - case StreamFormat::json_seq: - return next_delimited(true); - case StreamFormat::json_array: - return next_array_element(); + if (!doc_opt->has_value()) { + return error(std::move(doc_opt->error())); } - done_ = true; - return std::nullopt; + yyjson_val* root = yyjson_doc_get_root(doc_opt->value().get()); + const auto r = Reader(); + return Parser>::read(r, Reader::InputVarType(root)); } Iterator begin() { @@ -285,793 +375,7 @@ class StreamReader { std::default_sentinel_t end() const noexcept { return std::default_sentinel; } private: - static constexpr size_t kInitialWindow = 4096; - - enum class ArrayState { before_open, expect_first, expect_sep_end, closed }; - enum class SkipResult { found, eof, io_error, unclosed_comment }; - - static bool is_json_ws(const char _c) noexcept { - return _c == ' ' || _c == '\t' || _c == '\n' || _c == '\r'; - } - - static size_t safe_double(const size_t _n) noexcept { - constexpr size_t kMax = std::numeric_limits::max(); - return _n > kMax / 2 ? kMax : _n * 2; - } - - static size_t safe_inc(const size_t _n) noexcept { - constexpr size_t kMax = std::numeric_limits::max(); - return _n < kMax ? _n + 1 : kMax; - } - - const char* data_ptr() const noexcept { - return stream_ ? buf_.data() : input_.data(); - } - - size_t data_size() const noexcept { - return stream_ ? buf_.size() : input_.size(); - } - - size_t avail() const noexcept { return data_size() - pos_; } - - std::optional fail(const std::string& _msg) { - done_ = true; - return error(_msg); - } - - std::optional eof_or_io_error(const char* _eof_msg) { - done_ = true; - if (io_error_) { - return error("I/O error while reading JSON stream."); - } - return error(_eof_msg); - } - - void compact_buffer() { - if (!stream_ || pos_ == 0) { - return; - } - if (pos_ >= buf_.size()) { - buf_.clear(); - pos_ = 0; - } else if (pos_ >= chunk_size_ || pos_ * 2 >= buf_.size()) { - buf_.erase(0, pos_); - pos_ = 0; - } - } - - /// Reads up to `_requested` bytes from `*stream_` without blocking past the - /// first available OS read (or first line terminator on unbuffered streams). - size_t refill_raw(const size_t _requested, const bool _line_mode, - const bool _stop_at_rs) { - if (eof_ || !stream_) { - eof_ = true; - return 0; - } - if (_requested == 0) { - return 0; - } - if (stream_->bad() || (stream_->fail() && !stream_->eof())) { - io_error_ = true; - eof_ = true; - return 0; - } - std::streambuf* sb = stream_->rdbuf(); - if (!sb) { - eof_ = true; - return 0; - } - - compact_buffer(); - const size_t old_size = buf_.size(); - const size_t max_string_add = buf_.max_size() - old_size; - const size_t max_stream_add = - static_cast(std::numeric_limits::max()); - const size_t to_read = - std::min({_requested, max_string_add, max_stream_add}); - if (to_read == 0) { - return 0; - } - - using Traits = std::istream::traits_type; - auto drain_available = [&](const size_t _limit) -> size_t { - if (_limit == 0) { - return 0; - } - const std::streamsize avail_now = sb->in_avail(); - if (avail_now < 0) { - eof_ = true; - return 0; - } - if (avail_now == 0) { - return 0; - } - const size_t n_want = std::min(_limit, static_cast(avail_now)); - const size_t cur = buf_.size(); - const size_t needed = cur + n_want; - if (buf_.capacity() < needed) { - const size_t doubled = safe_double(buf_.capacity()); - buf_.reserve(std::min(buf_.max_size(), std::max(needed, doubled))); - } - buf_.resize(needed); - const std::streamsize got = - sb->sgetn(buf_.data() + cur, static_cast(n_want)); - const size_t n_got = got > 0 ? static_cast(got) : size_t{0}; - buf_.resize(cur + n_got); - return n_got; - }; - - size_t total_got = 0; - try { - const std::streamsize initial_avail = sb->in_avail(); - if (initial_avail < 0) { - eof_ = true; - return 0; - } - if (initial_avail > 0) { - total_got = drain_available(to_read); - } else { - // Nothing buffered: block once for the first byte. - const auto ch = sb->sbumpc(); - if (Traits::eq_int_type(ch, Traits::eof())) { - eof_ = true; - if (stream_->bad()) { - io_error_ = true; - } - return 0; - } - const char first = Traits::to_char_type(ch); - buf_.push_back(first); - total_got = 1; - - if (!(_line_mode && first == '\n') && to_read > 1) { - const std::streamsize after_avail = sb->in_avail(); - if (after_avail > 0) { - total_got += drain_available(to_read - 1); - } else if (after_avail == 0 && _line_mode) { - // Unbuffered stream in line mode: read up to '\n' (or '\x1e'). - while (total_got < to_read) { - const auto next_ch = sb->sbumpc(); - if (Traits::eq_int_type(next_ch, Traits::eof())) { - eof_ = true; - break; - } - const char c = Traits::to_char_type(next_ch); - buf_.push_back(c); - ++total_got; - if (c == '\n' || (_stop_at_rs && c == '\x1e')) { - break; - } - } - } - } - } - } catch (...) { - io_error_ = true; - eof_ = true; - return 0; - } - - if (stream_->bad()) { - io_error_ = true; - eof_ = true; - return 0; - } - return total_got; - } - - /// Refills while enforcing `max_record_bytes_` (allowing 1 lookahead byte - /// for delimiters after a record of exact size `max_record_bytes_`). - size_t refill_for_record(const size_t _requested, const bool _line_mode, - const bool _stop_at_rs) { - size_t allowed = _requested; - if (max_record_bytes_ > 0) { - const size_t cap = safe_inc(max_record_bytes_); - const size_t cur_avail = avail(); - if (cur_avail >= cap) { - record_too_large_ = true; - return 0; - } - allowed = std::min(allowed, cap - cur_avail); - } - return refill_raw(allowed, _line_mode, _stop_at_rs); - } - - bool skip_bom_if_needed() { - if (bom_checked_) { - return true; - } - bom_checked_ = true; - if ((flag_ & YYJSON_READ_ALLOW_BOM) == 0) { - return true; - } - const bool line_mode = (format_ != StreamFormat::json_array); - const bool stop_at_rs = (format_ == StreamFormat::json_seq); - if (avail() == 0 && !eof_) { - refill_raw(chunk_size_, line_mode, stop_at_rs); - if (io_error_) { - return false; - } - } - if (avail() == 0 || - static_cast(data_ptr()[pos_]) != 0xEF) { - return true; - } - while (avail() < 3 && !eof_) { - if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { - break; - } - } - if (io_error_) { - return false; - } - if (avail() >= 3 && - static_cast(data_ptr()[pos_]) == 0xEF && - static_cast(data_ptr()[pos_ + 1]) == 0xBB && - static_cast(data_ptr()[pos_ + 2]) == 0xBF) { - pos_ += 3; - compact_buffer(); - } - return true; - } - - SkipResult skip_ws(const bool _skip_rs = false) { - if (!skip_bom_if_needed()) { - return SkipResult::io_error; - } - const bool allow_comments = (flag_ & YYJSON_READ_ALLOW_COMMENTS) != 0; - const bool line_mode = (format_ != StreamFormat::json_array); - const bool stop_at_rs = (format_ == StreamFormat::json_seq); - - while (true) { - while (pos_ < data_size()) { - const char c = data_ptr()[pos_]; - if (is_json_ws(c) || (_skip_rs && c == '\x1e')) { - ++pos_; - continue; - } - if (allow_comments && c == '/') { - while (avail() < 2 && !eof_) { - if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { - break; - } - } - if (io_error_) { - return SkipResult::io_error; - } - if (avail() < 2) { - return SkipResult::found; - } - const char next_c = data_ptr()[pos_ + 1]; - if (next_c == '/') { - pos_ += 2; - while (true) { - while (pos_ < data_size()) { - const char cc = data_ptr()[pos_]; - if (cc == '\n' || cc == '\r') { - break; - } - ++pos_; - } - if (pos_ < data_size()) { - break; - } - if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { - return io_error_ ? SkipResult::io_error : SkipResult::eof; - } - } - continue; - } - if (next_c == '*') { - pos_ += 2; - bool closed = false; - while (!closed) { - while (pos_ < data_size()) { - if (data_ptr()[pos_] == '*') { - if (pos_ + 1 >= data_size()) { - if (eof_) { - return SkipResult::unclosed_comment; - } - if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { - return io_error_ ? SkipResult::io_error - : SkipResult::unclosed_comment; - } - continue; - } - if (data_ptr()[pos_ + 1] == '/') { - pos_ += 2; - closed = true; - break; - } - } - ++pos_; - } - if (!closed) { - if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { - return io_error_ ? SkipResult::io_error - : SkipResult::unclosed_comment; - } - } - } - continue; - } - } - return SkipResult::found; - } - if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { - return io_error_ ? SkipResult::io_error : SkipResult::eof; - } - } - } - - void advance_past_newline() { - const char* ptr = data_ptr() + pos_; - const size_t cur_avail = avail(); - if (const char* nl = - static_cast(std::memchr(ptr, '\n', cur_avail))) { - pos_ += static_cast(nl - ptr) + 1; - compact_buffer(); - return; - } - pos_ = data_size(); - compact_buffer(); - while (!eof_) { - if (refill_raw(chunk_size_, true, false) == 0) { - break; - } - const char* p = data_ptr() + pos_; - const size_t a = avail(); - if (const char* nl = static_cast(std::memchr(p, '\n', a))) { - pos_ += static_cast(nl - p) + 1; - compact_buffer(); - return; - } - pos_ = data_size(); - compact_buffer(); - } - } - - void resync_to_rs() { - const char* ptr = data_ptr() + pos_; - const size_t cur_avail = avail(); - if (cur_avail > 1) { - if (const char* rs = static_cast( - std::memchr(ptr + 1, '\x1e', cur_avail - 1))) { - pos_ += static_cast(rs - ptr); - compact_buffer(); - return; - } - } - pos_ = data_size(); - compact_buffer(); - while (!eof_) { - if (refill_raw(chunk_size_, true, true) == 0) { - break; - } - const char* p = data_ptr() + pos_; - const size_t a = avail(); - if (const char* rs = - static_cast(std::memchr(p, '\x1e', a))) { - pos_ += static_cast(rs - p); - compact_buffer(); - return; - } - pos_ = data_size(); - compact_buffer(); - } - } - - std::optional parse_delimited_value(const bool _is_seq) { - const yyjson_read_flag effective_flag = flag_ | YYJSON_READ_STOP_WHEN_DONE; - record_too_large_ = false; - size_t window = kInitialWindow; - size_t refill_step = chunk_size_; - bool expanded = false; - - while (true) { - if (avail() == 0) { - if (refill_for_record(refill_step, true, _is_seq) == 0) { - if (record_too_large_) { - return fail("JSON record exceeds maximum allowed size."); - } - if (io_error_) { - return fail("I/O error while reading JSON stream."); - } - done_ = true; - return std::nullopt; - } - continue; - } - - const char* ptr = data_ptr() + pos_; - const size_t cur_avail = avail(); - - const size_t probe_len = std::min(cur_avail, window); - const char* rs_ptr = - _is_seq - ? static_cast(std::memchr(ptr, '\x1e', probe_len)) - : nullptr; - const size_t nl_search_len = - rs_ptr ? static_cast(rs_ptr - ptr) : probe_len; - const char* nl_ptr = - !expanded - ? static_cast(std::memchr(ptr, '\n', nl_search_len)) - : nullptr; - - size_t slice_len = 0; - bool hard_boundary = false; - - if (nl_ptr) { - slice_len = static_cast(nl_ptr - ptr) + 1; - hard_boundary = false; - } else if (rs_ptr) { - slice_len = static_cast(rs_ptr - ptr); - hard_boundary = true; - } else if (!expanded && !eof_ && cur_avail < window) { - if (refill_for_record(refill_step, true, _is_seq) > 0) { - continue; - } - if (record_too_large_) { - return fail("JSON record exceeds maximum allowed size."); - } - if (io_error_) { - return fail("I/O error while reading JSON stream."); - } - slice_len = avail(); - hard_boundary = true; - } else { - slice_len = probe_len; - hard_boundary = (slice_len == cur_avail && eof_); - } - - bool hit_size_cap = false; - if (max_record_bytes_ > 0) { - const size_t allowed_slice = safe_inc(max_record_bytes_); - if (slice_len > allowed_slice) { - slice_len = allowed_slice; - hit_size_cap = true; - hard_boundary = false; - } else if (slice_len == allowed_slice && !nl_ptr && !rs_ptr && - !(slice_len == cur_avail && eof_)) { - hit_size_cap = true; - } - } - - if (slice_len == 0) { - if (hit_size_cap) { - return fail("JSON record exceeds maximum allowed size."); - } - done_ = true; - return std::nullopt; - } - - yyjson_read_err err{}; - yyjson_doc* doc = yyjson_read_opts(const_cast(ptr), slice_len, - effective_flag, nullptr, &err); - if (doc) { - const size_t read_size = yyjson_doc_get_read_size(doc); - yyjson_val* root = yyjson_doc_get_root(doc); - const bool is_self_delimiting = - yyjson_is_ctn(root) || yyjson_is_str(root); - - if (!is_self_delimiting && read_size == slice_len && !hard_boundary) { - yyjson_doc_free(doc); - if (hit_size_cap || - (max_record_bytes_ > 0 && read_size > max_record_bytes_)) { - return fail("JSON record exceeds maximum allowed size."); - } - expanded = true; - if (slice_len < cur_avail) { - window = std::max(safe_double(slice_len), safe_double(window)); - } else if (!eof_) { - refill_step = safe_double(refill_step); - window = std::max(safe_double(slice_len), window); - if (refill_for_record(refill_step, true, _is_seq) == 0) { - if (record_too_large_) { - return fail("JSON record exceeds maximum allowed size."); - } - if (io_error_) { - return fail("I/O error while reading JSON stream."); - } - } - } - continue; - } - - if (max_record_bytes_ > 0 && read_size > max_record_bytes_) { - yyjson_doc_free(doc); - return fail("JSON record exceeds maximum allowed size."); - } - - pos_ += read_size; - const auto r = Reader(); - auto res = - Parser>::read(r, Reader::InputVarType(root)); - yyjson_doc_free(doc); - compact_buffer(); - return res; - } - - const bool maybe_truncated = - (err.code == YYJSON_READ_ERROR_UNEXPECTED_END || - err.code == YYJSON_READ_ERROR_EMPTY_CONTENT); - - if (maybe_truncated) { - if (hit_size_cap || - (max_record_bytes_ > 0 && slice_len >= safe_inc(max_record_bytes_))) { - return fail("JSON record exceeds maximum allowed size."); - } - if (!hard_boundary) { - expanded = true; - if (slice_len < cur_avail) { - window = std::max(safe_double(slice_len), safe_double(window)); - continue; - } - if (!eof_) { - refill_step = safe_double(refill_step); - window = std::max(safe_double(slice_len), safe_double(window)); - if (refill_for_record(refill_step, true, _is_seq) > 0) { - continue; - } - if (record_too_large_) { - return fail("JSON record exceeds maximum allowed size."); - } - if (io_error_) { - return fail("I/O error while reading JSON stream."); - } - } - } - } - - const std::string err_msg = - "Could not parse document: " + - std::string(err.msg ? err.msg : "unknown error"); - if (_is_seq) { - resync_to_rs(); - } else { - advance_past_newline(); - } - if (io_error_) { - return fail("I/O error while reading JSON stream."); - } - return error(err_msg); - } - } - - std::optional parse_array_value() { - const yyjson_read_flag effective_flag = flag_ | YYJSON_READ_STOP_WHEN_DONE; - record_too_large_ = false; - size_t window = kInitialWindow; - size_t refill_step = chunk_size_; - - while (true) { - if (avail() == 0) { - if (refill_for_record(refill_step, false, false) == 0) { - if (record_too_large_) { - return fail("JSON record exceeds maximum allowed size."); - } - return eof_or_io_error( - "Could not parse document: unexpected end of data"); - } - continue; - } - - const char* ptr = data_ptr() + pos_; - const size_t cur_avail = avail(); - size_t slice_len = std::min(cur_avail, window); - bool hit_size_cap = false; - - if (max_record_bytes_ > 0) { - const size_t allowed_slice = safe_inc(max_record_bytes_); - if (slice_len > allowed_slice) { - slice_len = allowed_slice; - hit_size_cap = true; - } else if (slice_len == allowed_slice && - !(slice_len == cur_avail && eof_)) { - hit_size_cap = true; - } - } - - yyjson_read_err err{}; - yyjson_doc* doc = yyjson_read_opts(const_cast(ptr), slice_len, - effective_flag, nullptr, &err); - if (doc) { - const size_t read_size = yyjson_doc_get_read_size(doc); - yyjson_val* root = yyjson_doc_get_root(doc); - const bool is_self_delimiting = - yyjson_is_ctn(root) || yyjson_is_str(root); - - const bool more_bytes_possible = (slice_len < cur_avail) || !eof_; - if (!is_self_delimiting && read_size == slice_len && - more_bytes_possible) { - yyjson_doc_free(doc); - if (hit_size_cap || - (max_record_bytes_ > 0 && read_size > max_record_bytes_)) { - return fail("JSON record exceeds maximum allowed size."); - } - if (slice_len < cur_avail) { - window = safe_double(window); - } else { - refill_step = safe_double(refill_step); - window = std::max(safe_double(slice_len), window); - if (refill_for_record(refill_step, false, false) == 0) { - if (record_too_large_) { - return fail("JSON record exceeds maximum allowed size."); - } - if (io_error_) { - return fail("I/O error while reading JSON stream."); - } - } - } - continue; - } - - if (max_record_bytes_ > 0 && read_size > max_record_bytes_) { - yyjson_doc_free(doc); - return fail("JSON record exceeds maximum allowed size."); - } - - pos_ += read_size; - const auto r = Reader(); - auto res = - Parser>::read(r, Reader::InputVarType(root)); - yyjson_doc_free(doc); - compact_buffer(); - return res; - } - - const bool maybe_truncated = - (err.code == YYJSON_READ_ERROR_UNEXPECTED_END || - err.code == YYJSON_READ_ERROR_EMPTY_CONTENT); - if (maybe_truncated) { - if (hit_size_cap || - (max_record_bytes_ > 0 && slice_len >= safe_inc(max_record_bytes_))) { - return fail("JSON record exceeds maximum allowed size."); - } - if (slice_len < cur_avail) { - window = safe_double(window); - continue; - } - if (!eof_) { - refill_step = safe_double(refill_step); - window = std::max(safe_double(slice_len), window); - if (refill_for_record(refill_step, false, false) > 0) { - continue; - } - if (record_too_large_) { - return fail("JSON record exceeds maximum allowed size."); - } - if (io_error_) { - return fail("I/O error while reading JSON stream."); - } - } - } - - done_ = true; - return error("Could not parse document: " + - std::string(err.msg ? err.msg : "unknown error")); - } - } - - std::optional next_delimited(const bool _skip_rs) { - const auto skipped = skip_ws(_skip_rs); - if (skipped == SkipResult::eof) { - done_ = true; - return std::nullopt; - } - if (skipped == SkipResult::io_error) { - return fail("I/O error while reading JSON stream."); - } - if (skipped == SkipResult::unclosed_comment) { - return fail("Unclosed multi-line comment in JSON stream."); - } - return parse_delimited_value(_skip_rs); - } - - std::optional finish_array() { - ++pos_; // consume ']' - array_state_ = ArrayState::closed; - done_ = true; - const auto skipped = skip_ws(false); - if (skipped == SkipResult::found) { - return error( - "Unexpected trailing content after closing ']' of JSON array."); - } - if (skipped == SkipResult::io_error) { - return error("I/O error while reading JSON stream."); - } - if (skipped == SkipResult::unclosed_comment) { - return error("Unclosed multi-line comment in JSON stream."); - } - return std::nullopt; - } - - std::optional next_array_element() { - auto handle_skip_error = [&](const SkipResult _sr, - const char* _eof_msg) -> std::optional { - if (_sr == SkipResult::unclosed_comment) { - return fail("Unclosed multi-line comment in JSON stream."); - } - return eof_or_io_error(_eof_msg); - }; - - if (array_state_ == ArrayState::before_open) { - const auto skipped = skip_ws(false); - if (skipped != SkipResult::found) { - return handle_skip_error( - skipped, "Expected '[' at start of JSON array, got end of input."); - } - if (data_ptr()[pos_] != '[') { - return fail("Expected '[' at start of JSON array."); - } - ++pos_; - array_state_ = ArrayState::expect_first; - } - - if (array_state_ == ArrayState::expect_first) { - const auto skipped = skip_ws(false); - if (skipped != SkipResult::found) { - return handle_skip_error( - skipped, - "Unexpected end of input in JSON array: expected ']' or value."); - } - if (data_ptr()[pos_] == ']') { - return finish_array(); - } - auto res = parse_array_value(); - if (!done_) { - array_state_ = ArrayState::expect_sep_end; - } - return res; - } - - if (array_state_ == ArrayState::expect_sep_end) { - const auto skipped = skip_ws(false); - if (skipped != SkipResult::found) { - return handle_skip_error( - skipped, - "Unexpected end of input in JSON array: expected ',' or ']'."); - } - if (data_ptr()[pos_] == ']') { - return finish_array(); - } - if (data_ptr()[pos_] != ',') { - return fail("Expected ',' or ']' in JSON array."); - } - ++pos_; // consume ',' - const auto after_comma = skip_ws(false); - if (after_comma != SkipResult::found) { - return handle_skip_error( - after_comma, "Unexpected end of input in JSON array after ','."); - } - if (data_ptr()[pos_] == ']') { - if (flag_ & YYJSON_READ_ALLOW_TRAILING_COMMAS) { - return finish_array(); - } - return fail("Trailing comma is not allowed in JSON array."); - } - return parse_array_value(); - } - - done_ = true; - return std::nullopt; - } - - std::istream* stream_; - StreamFormat format_; - yyjson_read_flag flag_; - size_t chunk_size_; - size_t max_record_bytes_; - std::string_view input_; - std::string buf_; - size_t pos_ = 0; - bool eof_ = false; - bool io_error_ = false; - bool record_too_large_ = false; - bool bom_checked_ = false; - bool done_ = false; - bool invalid_flag_ = false; - ArrayState array_state_ = ArrayState::before_open; + detail::StreamReaderEngine engine_; std::optional current_; }; diff --git a/src/reflectcpp_json.cpp b/src/reflectcpp_json.cpp index 7b7bd66e6..20c22d344 100644 --- a/src/reflectcpp_json.cpp +++ b/src/reflectcpp_json.cpp @@ -30,4 +30,5 @@ SOFTWARE. // compilation. #include "rfl/json/Writer.cpp" +#include "rfl/json/stream.cpp" #include "rfl/json/to_schema.cpp" diff --git a/src/rfl/json/stream.cpp b/src/rfl/json/stream.cpp new file mode 100644 index 000000000..1c0acbb6f --- /dev/null +++ b/src/rfl/json/stream.cpp @@ -0,0 +1,980 @@ +/* + +MIT License + +Copyright (c) 2023-2024 Code17 GmbH + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +*/ + +#include "rfl/json/stream.hpp" + +#include +#include +#include +#include + +namespace rfl::json::detail { + +namespace { + +bool is_json_ws(const char _c, const bool _allow_ext_ws) noexcept { + if (_c == ' ' || _c == '\t' || _c == '\n' || _c == '\r') { + return true; + } + return _allow_ext_ws && (_c == '\v' || _c == '\f'); +} + +bool is_primitive_char(const char _c) noexcept { + return (_c >= '0' && _c <= '9') || (_c >= 'a' && _c <= 'z') || + (_c >= 'A' && _c <= 'Z') || _c == '+' || _c == '-' || _c == '.'; +} + +size_t safe_double(const size_t _n) noexcept { + constexpr size_t kMax = std::numeric_limits::max(); + return _n > kMax / 2 ? kMax : _n * 2; +} + +size_t safe_inc(const size_t _n) noexcept { + constexpr size_t kMax = std::numeric_limits::max(); + return _n < kMax ? _n + 1 : kMax; +} + +} // namespace + +StreamReaderEngine::StreamReaderEngine(std::istream& _stream, + const StreamFormat _format, + const yyjson_read_flag _flag, + const size_t _chunk_size, + const size_t _max_record_bytes) + : stream_(&_stream), + format_(_format), + flag_(_flag), + chunk_size_(_chunk_size > 0 ? _chunk_size : 1), + max_record_bytes_(_max_record_bytes), + invalid_flag_((_flag & YYJSON_READ_INSITU) != 0) {} + +StreamReaderEngine::StreamReaderEngine(const std::string_view _input, + const StreamFormat _format, + const yyjson_read_flag _flag, + const size_t _max_record_bytes) + : stream_(nullptr), + format_(_format), + flag_(_flag), + chunk_size_(0), + max_record_bytes_(_max_record_bytes), + input_(_input), + eof_(true), + invalid_flag_((_flag & YYJSON_READ_INSITU) != 0) {} + +std::optional> StreamReaderEngine::next_doc() { + if (done_) { + return std::nullopt; + } + if (invalid_flag_) { + return fail("YYJSON_READ_INSITU is not supported"); + } + switch (format_) { + case StreamFormat::ndjson: + return next_delimited(false); + case StreamFormat::json_seq: + return next_delimited(true); + case StreamFormat::json_array: + return next_array_element(); + } + done_ = true; + return std::nullopt; +} + +const char* StreamReaderEngine::data_ptr() const noexcept { + return stream_ ? buf_.data() : input_.data(); +} + +size_t StreamReaderEngine::data_size() const noexcept { + return stream_ ? buf_.size() : input_.size(); +} + +size_t StreamReaderEngine::avail() const noexcept { return data_size() - pos_; } + +std::optional> StreamReaderEngine::fail( + const std::string& _msg) { + done_ = true; + return error(_msg); +} + +std::optional> StreamReaderEngine::eof_or_io_error( + const char* _eof_msg) { + done_ = true; + if (io_error_) { + return error("I/O error while reading JSON stream."); + } + return error(_eof_msg); +} + +void StreamReaderEngine::compact_buffer() { + if (!stream_ || pos_ == 0) { + return; + } + if (pos_ >= buf_.size()) { + buf_.clear(); + pos_ = 0; + } else if (pos_ >= chunk_size_ || pos_ * 2 >= buf_.size()) { + buf_.erase(0, pos_); + pos_ = 0; + } +} + +size_t StreamReaderEngine::refill_raw(const size_t _requested, + const bool _line_mode, + const bool _stop_at_rs) { + if (eof_ || !stream_) { + eof_ = true; + return 0; + } + if (_requested == 0) { + return 0; + } + if (stream_->bad() || (stream_->fail() && !stream_->eof())) { + io_error_ = true; + eof_ = true; + return 0; + } + std::streambuf* sb = stream_->rdbuf(); + if (!sb) { + eof_ = true; + return 0; + } + + compact_buffer(); + const size_t old_size = buf_.size(); + const size_t max_string_add = buf_.max_size() - old_size; + const size_t max_stream_add = + static_cast(std::numeric_limits::max()); + const size_t to_read = + std::min({_requested, max_string_add, max_stream_add}); + if (to_read == 0) { + return 0; + } + + using Traits = std::istream::traits_type; + auto drain_available = [&](const size_t _limit) -> size_t { + if (_limit == 0) { + return 0; + } + const std::streamsize avail_now = sb->in_avail(); + if (avail_now < 0) { + eof_ = true; + return 0; + } + if (avail_now == 0) { + return 0; + } + const size_t n_want = std::min(_limit, static_cast(avail_now)); + const size_t cur = buf_.size(); + const size_t needed = cur + n_want; + if (buf_.capacity() < needed) { + const size_t doubled = safe_double(buf_.capacity()); + buf_.reserve(std::min(buf_.max_size(), std::max(needed, doubled))); + } + buf_.resize(needed); + const std::streamsize got = + sb->sgetn(buf_.data() + cur, static_cast(n_want)); + const size_t n_got = got > 0 ? static_cast(got) : size_t{0}; + buf_.resize(cur + n_got); + return n_got; + }; + + size_t total_got = 0; + try { + const std::streamsize initial_avail = sb->in_avail(); + if (initial_avail < 0) { + eof_ = true; + return 0; + } + if (initial_avail > 0) { + total_got = drain_available(to_read); + } else { + // Nothing buffered: block once for the first byte. + const auto ch = sb->sbumpc(); + if (Traits::eq_int_type(ch, Traits::eof())) { + eof_ = true; + if (stream_->bad()) { + io_error_ = true; + } + return 0; + } + const char first = Traits::to_char_type(ch); + buf_.push_back(first); + total_got = 1; + + if (!(_line_mode && first == '\n') && to_read > 1) { + const std::streamsize after_avail = sb->in_avail(); + if (after_avail > 0) { + total_got += drain_available(to_read - 1); + } else if (after_avail == 0 && _line_mode) { + // Unbuffered stream in line mode: read up to '\n' (or '\x1e'). + while (total_got < to_read) { + const auto next_ch = sb->sbumpc(); + if (Traits::eq_int_type(next_ch, Traits::eof())) { + eof_ = true; + break; + } + const char c = Traits::to_char_type(next_ch); + buf_.push_back(c); + ++total_got; + if (c == '\n' || (_stop_at_rs && c == '\x1e')) { + break; + } + } + } + } + } + } catch (...) { + io_error_ = true; + eof_ = true; + return 0; + } + + if (stream_->bad()) { + io_error_ = true; + eof_ = true; + return 0; + } + return total_got; +} + +size_t StreamReaderEngine::refill_for_record(const size_t _requested, + const bool _line_mode, + const bool _stop_at_rs) { + size_t allowed = _requested; + if (max_record_bytes_ > 0) { + const size_t cap = safe_inc(max_record_bytes_); + const size_t cur_avail = avail(); + if (cur_avail >= cap) { + return 0; + } + allowed = std::min(allowed, cap - cur_avail); + } + return refill_raw(allowed, _line_mode, _stop_at_rs); +} + +bool StreamReaderEngine::skip_bom_if_needed() { + if (bom_checked_) { + return true; + } + bom_checked_ = true; + if ((flag_ & YYJSON_READ_ALLOW_BOM) == 0) { + return true; + } + const bool line_mode = (format_ != StreamFormat::json_array); + const bool stop_at_rs = (format_ == StreamFormat::json_seq); + if (avail() == 0 && !eof_) { + refill_raw(chunk_size_, line_mode, stop_at_rs); + if (io_error_) { + return false; + } + } + if (avail() == 0 || + static_cast(data_ptr()[pos_]) != 0xEF) { + return true; + } + while (avail() < 3 && !eof_) { + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + break; + } + } + if (io_error_) { + return false; + } + if (avail() >= 3 && + static_cast(data_ptr()[pos_]) == 0xEF && + static_cast(data_ptr()[pos_ + 1]) == 0xBB && + static_cast(data_ptr()[pos_ + 2]) == 0xBF) { + pos_ += 3; + compact_buffer(); + } + return true; +} + +StreamReaderEngine::SkipResult StreamReaderEngine::skip_ws( + const bool _skip_rs) { + if (!skip_bom_if_needed()) { + return SkipResult::io_error; + } + const bool allow_comments = (flag_ & YYJSON_READ_ALLOW_COMMENTS) != 0; + const bool allow_ext_ws = (flag_ & YYJSON_READ_ALLOW_EXT_WHITESPACE) != 0; + const bool line_mode = (format_ != StreamFormat::json_array); + const bool stop_at_rs = (format_ == StreamFormat::json_seq); + + while (true) { + while (pos_ < data_size()) { + const char c = data_ptr()[pos_]; + if (is_json_ws(c, allow_ext_ws) || (_skip_rs && c == '\x1e')) { + ++pos_; + continue; + } + if (allow_comments && c == '/') { + while (avail() < 2 && !eof_) { + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + break; + } + } + if (io_error_) { + return SkipResult::io_error; + } + if (avail() < 2) { + return SkipResult::found; + } + const char next_c = data_ptr()[pos_ + 1]; + if (next_c == '/') { + pos_ += 2; + while (true) { + while (pos_ < data_size()) { + const char cc = data_ptr()[pos_]; + if (cc == '\n' || cc == '\r') { + break; + } + ++pos_; + } + if (pos_ < data_size()) { + break; + } + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + return io_error_ ? SkipResult::io_error : SkipResult::eof; + } + } + continue; + } + if (next_c == '*') { + pos_ += 2; + bool closed = false; + while (!closed) { + while (pos_ < data_size()) { + if (data_ptr()[pos_] == '*') { + if (pos_ + 1 >= data_size()) { + if (eof_) { + return SkipResult::unclosed_comment; + } + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + return io_error_ ? SkipResult::io_error + : SkipResult::unclosed_comment; + } + continue; + } + if (data_ptr()[pos_ + 1] == '/') { + pos_ += 2; + closed = true; + break; + } + } + ++pos_; + } + if (!closed) { + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + return io_error_ ? SkipResult::io_error + : SkipResult::unclosed_comment; + } + } + } + continue; + } + } + return SkipResult::found; + } + if (refill_raw(chunk_size_, line_mode, stop_at_rs) == 0) { + return io_error_ ? SkipResult::io_error : SkipResult::eof; + } + } +} + +void StreamReaderEngine::advance_past_newline() { + const char* ptr = data_ptr() + pos_; + const size_t cur_avail = avail(); + if (const char* nl = + static_cast(std::memchr(ptr, '\n', cur_avail))) { + pos_ += static_cast(nl - ptr) + 1; + compact_buffer(); + return; + } + pos_ = data_size(); + compact_buffer(); + while (!eof_) { + if (refill_raw(chunk_size_, true, false) == 0) { + break; + } + const char* p = data_ptr() + pos_; + const size_t a = avail(); + if (const char* nl = static_cast(std::memchr(p, '\n', a))) { + pos_ += static_cast(nl - p) + 1; + compact_buffer(); + return; + } + pos_ = data_size(); + compact_buffer(); + } +} + +void StreamReaderEngine::resync_to_rs() { + const char* ptr = data_ptr() + pos_; + const size_t cur_avail = avail(); + if (cur_avail > 1) { + if (const char* rs = static_cast( + std::memchr(ptr + 1, '\x1e', cur_avail - 1))) { + pos_ += static_cast(rs - ptr); + compact_buffer(); + return; + } + } + pos_ = data_size(); + compact_buffer(); + while (!eof_) { + if (refill_raw(chunk_size_, true, true) == 0) { + break; + } + const char* p = data_ptr() + pos_; + const size_t a = avail(); + if (const char* rs = static_cast(std::memchr(p, '\x1e', a))) { + pos_ += static_cast(rs - p); + compact_buffer(); + return; + } + pos_ = data_size(); + compact_buffer(); + } +} + +StreamReaderEngine::ScanResult StreamReaderEngine::scan_value( + const bool _line_mode, const bool _is_seq, const bool _check_first_nl, + std::string* _first_nl_err) { + const bool allow_comments = (flag_ & YYJSON_READ_ALLOW_COMMENTS) != 0; + const bool allow_single_quote = + (flag_ & YYJSON_READ_ALLOW_SINGLE_QUOTED_STR) != 0; + const bool allow_ext_escape = (flag_ & YYJSON_READ_ALLOW_EXT_ESCAPE) != 0; + const char c0 = data_ptr()[pos_]; + + // Case 1: JSON object or array container. + if (c0 == '{' || c0 == '[') { + size_t scan_offset = 0; + size_t depth = 0; + char quote = 0; + bool escape = false; + CommentMode comment = CommentMode::none; + bool checked_first_nl = !_check_first_nl; + size_t refill_step = chunk_size_; + + while (true) { + const char* ptr = data_ptr() + pos_; + const size_t cur_avail = avail(); + const size_t scan_limit = max_record_bytes_ > 0 + ? std::min(cur_avail, max_record_bytes_) + : cur_avail; + + while (scan_offset < scan_limit) { + const char c = ptr[scan_offset]; + + if (_is_seq && c == '\x1e') { + return ScanResult{ScanOutcome::hard_boundary, scan_offset}; + } + + if (comment != CommentMode::none) { + if (comment == CommentMode::slash) { + if (c == '/') { + comment = CommentMode::line; + ++scan_offset; + continue; + } + if (c == '*') { + comment = CommentMode::block; + ++scan_offset; + continue; + } + comment = CommentMode::none; + // Not a comment; fall through to process `c` normally. + } else if (comment == CommentMode::line) { + ++scan_offset; + if (c == '\n' || c == '\r') { + comment = CommentMode::none; + if (c == '\n' && !checked_first_nl) { + checked_first_nl = true; + yyjson_read_err err{}; + yyjson_doc* probe = yyjson_read_opts( + const_cast(ptr), scan_offset, + flag_ | YYJSON_READ_STOP_WHEN_DONE, nullptr, &err); + if (probe) { + yyjson_doc_free(probe); + } else if (err.code != YYJSON_READ_ERROR_UNEXPECTED_END && + err.code != YYJSON_READ_ERROR_EMPTY_CONTENT) { + if (_first_nl_err) { + *_first_nl_err = err.msg ? err.msg : "unknown error"; + } + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } + } + } + continue; + } else if (comment == CommentMode::block) { + if (c == '*') { + comment = CommentMode::block_star; + } + ++scan_offset; + continue; + } else { // CommentMode::block_star + if (c == '/') { + comment = CommentMode::none; + } else if (c != '*') { + comment = CommentMode::block; + } + ++scan_offset; + continue; + } + } + + if (quote != 0) { + if (escape) { + escape = false; + ++scan_offset; + continue; + } + if (c == '\\') { + escape = true; + ++scan_offset; + continue; + } + if (c == quote) { + quote = 0; + ++scan_offset; + continue; + } + if (!allow_ext_escape && (c == '\n' || c == '\r')) { + ++scan_offset; + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } + ++scan_offset; + continue; + } + + if (c == '"' || (allow_single_quote && c == '\'')) { + quote = c; + ++scan_offset; + continue; + } + + if (allow_comments && c == '/') { + comment = CommentMode::slash; + ++scan_offset; + continue; + } + + if (c == '{' || c == '[') { + ++depth; + ++scan_offset; + continue; + } + + if (c == '}' || c == ']') { + if (depth > 0) { + --depth; + } + ++scan_offset; + if (depth == 0) { + return ScanResult{ScanOutcome::complete, scan_offset}; + } + continue; + } + + ++scan_offset; + if (c == '\n' && !checked_first_nl) { + checked_first_nl = true; + yyjson_read_err err{}; + yyjson_doc* probe = yyjson_read_opts( + const_cast(ptr), scan_offset, + flag_ | YYJSON_READ_STOP_WHEN_DONE, nullptr, &err); + if (probe) { + yyjson_doc_free(probe); + } else if (err.code != YYJSON_READ_ERROR_UNEXPECTED_END && + err.code != YYJSON_READ_ERROR_EMPTY_CONTENT) { + if (_first_nl_err) { + *_first_nl_err = err.msg ? err.msg : "unknown error"; + } + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } + } + } + + if (max_record_bytes_ > 0 && scan_offset >= max_record_bytes_) { + if (avail() <= max_record_bytes_ && !eof_) { + (void)refill_for_record(refill_step, _line_mode, _is_seq); + if (io_error_) { + return ScanResult{ScanOutcome::io_error, scan_offset}; + } + } + if (avail() > max_record_bytes_) { + if (_is_seq && data_ptr()[pos_ + max_record_bytes_] == '\x1e') { + return ScanResult{ScanOutcome::hard_boundary, scan_offset}; + } + return ScanResult{ScanOutcome::too_large, scan_offset}; + } + return ScanResult{ScanOutcome::eof_truncated, scan_offset}; + } + + if (eof_) { + return ScanResult{ScanOutcome::eof_truncated, scan_offset}; + } + + const size_t got = refill_for_record(refill_step, _line_mode, _is_seq); + if (io_error_) { + return ScanResult{ScanOutcome::io_error, scan_offset}; + } + if (got == 0) { + return ScanResult{ScanOutcome::eof_truncated, scan_offset}; + } + refill_step = safe_double(refill_step); + } + } + + // Case 2: JSON string literal. + if (c0 == '"' || (allow_single_quote && c0 == '\'')) { + const char quote = c0; + size_t scan_offset = 1; + bool escape = false; + size_t refill_step = chunk_size_; + + while (true) { + const char* ptr = data_ptr() + pos_; + const size_t cur_avail = avail(); + const size_t scan_limit = max_record_bytes_ > 0 + ? std::min(cur_avail, max_record_bytes_) + : cur_avail; + + while (scan_offset < scan_limit) { + const char c = ptr[scan_offset]; + if (_is_seq && c == '\x1e') { + return ScanResult{ScanOutcome::hard_boundary, scan_offset}; + } + if (escape) { + escape = false; + ++scan_offset; + continue; + } + if (c == '\\') { + escape = true; + ++scan_offset; + continue; + } + if (c == quote) { + ++scan_offset; + return ScanResult{ScanOutcome::complete, scan_offset}; + } + if (!allow_ext_escape && (c == '\n' || c == '\r')) { + ++scan_offset; + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } + ++scan_offset; + } + + if (max_record_bytes_ > 0 && scan_offset >= max_record_bytes_) { + if (avail() <= max_record_bytes_ && !eof_) { + (void)refill_for_record(refill_step, _line_mode, _is_seq); + if (io_error_) { + return ScanResult{ScanOutcome::io_error, scan_offset}; + } + } + if (avail() > max_record_bytes_) { + if (_is_seq && data_ptr()[pos_ + max_record_bytes_] == '\x1e') { + return ScanResult{ScanOutcome::hard_boundary, scan_offset}; + } + return ScanResult{ScanOutcome::too_large, scan_offset}; + } + return ScanResult{ScanOutcome::eof_truncated, scan_offset}; + } + + if (eof_) { + return ScanResult{ScanOutcome::eof_truncated, scan_offset}; + } + + const size_t got = refill_for_record(refill_step, _line_mode, _is_seq); + if (io_error_) { + return ScanResult{ScanOutcome::io_error, scan_offset}; + } + if (got == 0) { + return ScanResult{ScanOutcome::eof_truncated, scan_offset}; + } + refill_step = safe_double(refill_step); + } + } + + // Case 3: JSON primitive (number, boolean, null, NaN/Infinity) or bad token. + if (!is_primitive_char(c0)) { + return ScanResult{ScanOutcome::syntax_break, 1}; + } + + size_t scan_offset = 1; + size_t refill_step = chunk_size_; + while (true) { + const char* ptr = data_ptr() + pos_; + const size_t cur_avail = avail(); + const size_t scan_limit = max_record_bytes_ > 0 + ? std::min(cur_avail, max_record_bytes_) + : cur_avail; + + while (scan_offset < scan_limit) { + if (!is_primitive_char(ptr[scan_offset])) { + return ScanResult{ScanOutcome::complete, scan_offset}; + } + ++scan_offset; + } + + if (max_record_bytes_ > 0 && scan_offset >= max_record_bytes_) { + if (avail() <= max_record_bytes_ && !eof_) { + (void)refill_for_record(refill_step, _line_mode, _is_seq); + if (io_error_) { + return ScanResult{ScanOutcome::io_error, scan_offset}; + } + } + if (avail() > max_record_bytes_ && + is_primitive_char(data_ptr()[pos_ + max_record_bytes_])) { + return ScanResult{ScanOutcome::too_large, scan_offset}; + } + return ScanResult{ScanOutcome::complete, scan_offset}; + } + + if (eof_) { + return ScanResult{ScanOutcome::complete, scan_offset}; + } + + const size_t got = refill_for_record(refill_step, _line_mode, _is_seq); + if (io_error_) { + return ScanResult{ScanOutcome::io_error, scan_offset}; + } + if (got == 0) { + return ScanResult{ScanOutcome::complete, scan_offset}; + } + refill_step = safe_double(refill_step); + } +} + +std::optional> StreamReaderEngine::parse_delimited_value( + const bool _is_seq) { + if (avail() == 0) { + done_ = true; + return std::nullopt; + } + + std::string first_nl_err; + const ScanResult scan = scan_value(true, _is_seq, !_is_seq, &first_nl_err); + + if (scan.outcome == ScanOutcome::too_large) { + return fail("JSON record exceeds maximum allowed size."); + } + if (scan.outcome == ScanOutcome::io_error) { + return fail("I/O error while reading JSON stream."); + } + + if (scan.outcome == ScanOutcome::syntax_break && !first_nl_err.empty()) { + const std::string err_msg = "Could not parse document: " + first_nl_err; + if (_is_seq) { + resync_to_rs(); + } else { + advance_past_newline(); + } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } + return error(err_msg); + } + + if (scan.slice_len == 0) { + done_ = true; + return std::nullopt; + } + + // Always compute ptr fresh after scan_value (which may refill/compact buf_). + const char* ptr = data_ptr() + pos_; + yyjson_read_err err{}; + YYJsonDocPtr doc(yyjson_read_opts(const_cast(ptr), scan.slice_len, + flag_, nullptr, &err)); + if (doc) { + const size_t read_size = yyjson_doc_get_read_size(doc.get()); + if (max_record_bytes_ > 0 && read_size > max_record_bytes_) { + return fail("JSON record exceeds maximum allowed size."); + } + pos_ += read_size; + compact_buffer(); + return Result(std::move(doc)); + } + + const std::string err_msg = + "Could not parse document: " + + std::string(err.msg ? err.msg : "unknown error"); + if (_is_seq) { + resync_to_rs(); + } else { + advance_past_newline(); + } + if (io_error_) { + return fail("I/O error while reading JSON stream."); + } + return error(err_msg); +} + +std::optional> StreamReaderEngine::parse_array_value() { + if (avail() == 0) { + return eof_or_io_error("Could not parse document: unexpected end of data"); + } + + const ScanResult scan = scan_value(false, false, false, nullptr); + + if (scan.outcome == ScanOutcome::too_large) { + return fail("JSON record exceeds maximum allowed size."); + } + if (scan.outcome == ScanOutcome::io_error) { + return fail("I/O error while reading JSON stream."); + } + if (scan.slice_len == 0) { + return eof_or_io_error("Could not parse document: unexpected end of data"); + } + + // Always compute ptr fresh after scan_value (which may refill/compact buf_). + const char* ptr = data_ptr() + pos_; + yyjson_read_err err{}; + YYJsonDocPtr doc(yyjson_read_opts(const_cast(ptr), scan.slice_len, + flag_, nullptr, &err)); + if (doc) { + const size_t read_size = yyjson_doc_get_read_size(doc.get()); + if (max_record_bytes_ > 0 && read_size > max_record_bytes_) { + return fail("JSON record exceeds maximum allowed size."); + } + pos_ += read_size; + compact_buffer(); + return Result(std::move(doc)); + } + + done_ = true; + return error("Could not parse document: " + + std::string(err.msg ? err.msg : "unknown error")); +} + +std::optional> StreamReaderEngine::next_delimited( + const bool _skip_rs) { + const auto skipped = skip_ws(_skip_rs); + if (skipped == SkipResult::eof) { + done_ = true; + return std::nullopt; + } + if (skipped == SkipResult::io_error) { + return fail("I/O error while reading JSON stream."); + } + if (skipped == SkipResult::unclosed_comment) { + return fail("Unclosed multi-line comment in JSON stream."); + } + return parse_delimited_value(_skip_rs); +} + +std::optional> StreamReaderEngine::finish_array() { + ++pos_; // consume ']' + array_state_ = ArrayState::closed; + done_ = true; + const auto skipped = skip_ws(false); + if (skipped == SkipResult::found) { + return error( + "Unexpected trailing content after closing ']' of JSON array."); + } + if (skipped == SkipResult::io_error) { + return error("I/O error while reading JSON stream."); + } + if (skipped == SkipResult::unclosed_comment) { + return error("Unclosed multi-line comment in JSON stream."); + } + return std::nullopt; +} + +std::optional> StreamReaderEngine::next_array_element() { + auto handle_skip_error = + [&](const SkipResult _sr, + const char* _eof_msg) -> std::optional> { + if (_sr == SkipResult::unclosed_comment) { + return fail("Unclosed multi-line comment in JSON stream."); + } + return eof_or_io_error(_eof_msg); + }; + + if (array_state_ == ArrayState::before_open) { + const auto skipped = skip_ws(false); + if (skipped != SkipResult::found) { + return handle_skip_error( + skipped, "Expected '[' at start of JSON array, got end of input."); + } + if (data_ptr()[pos_] != '[') { + return fail("Expected '[' at start of JSON array."); + } + ++pos_; + array_state_ = ArrayState::expect_first; + } + + if (array_state_ == ArrayState::expect_first) { + const auto skipped = skip_ws(false); + if (skipped != SkipResult::found) { + return handle_skip_error( + skipped, + "Unexpected end of input in JSON array: expected ']' or value."); + } + if (data_ptr()[pos_] == ']') { + return finish_array(); + } + auto res = parse_array_value(); + if (!done_) { + array_state_ = ArrayState::expect_sep_end; + } + return res; + } + + if (array_state_ == ArrayState::expect_sep_end) { + const auto skipped = skip_ws(false); + if (skipped != SkipResult::found) { + return handle_skip_error( + skipped, + "Unexpected end of input in JSON array: expected ',' or ']'."); + } + if (data_ptr()[pos_] == ']') { + return finish_array(); + } + if (data_ptr()[pos_] != ',') { + return fail("Expected ',' or ']' in JSON array."); + } + ++pos_; // consume ',' + const auto after_comma = skip_ws(false); + if (after_comma != SkipResult::found) { + return handle_skip_error( + after_comma, "Unexpected end of input in JSON array after ','."); + } + if (data_ptr()[pos_] == ']') { + if (flag_ & YYJSON_READ_ALLOW_TRAILING_COMMAS) { + return finish_array(); + } + return fail("Trailing comma is not allowed in JSON array."); + } + return parse_array_value(); + } + + done_ = true; + return std::nullopt; +} + +} // namespace rfl::json::detail diff --git a/tests/json/test_stream.cpp b/tests/json/test_stream.cpp index fd392fd2f..9440ad45a 100644 --- a/tests/json/test_stream.cpp +++ b/tests/json/test_stream.cpp @@ -33,6 +33,37 @@ struct MoveOnlyRow { std::unique_ptr label; }; +struct IdOnly { + int id; + bool operator==(const IdOnly&) const = default; +}; + +// Unbuffered streambuf: yields 1 byte per underflow() with in_avail() == 0, +// simulating unbuffered streams such as synced std::cin. +class UnbufferedBuf : public std::streambuf { + public: + explicit UnbufferedBuf(std::string _data) : data_(std::move(_data)) {} + + protected: + int_type underflow() override { + if (idx_ >= data_.size()) { + return traits_type::eof(); + } + return traits_type::to_int_type(data_[idx_]); + } + + int_type uflow() override { + if (idx_ >= data_.size()) { + return traits_type::eof(); + } + return traits_type::to_int_type(data_[idx_++]); + } + + private: + std::string data_; + size_t idx_ = 0; +}; + static_assert(std::input_iterator::Iterator>); static_assert(std::ranges::input_range>); static_assert( @@ -287,7 +318,8 @@ TEST(json, test_stream_writer_errors_and_flags) { } } - // Bad / failbit ostream returns rfl::Error from write(), flush(), finish() + // Bad / failbit ostream returns rfl::Error from write(), flush(), finish(), + // and a failed finish() continues returning Error on retry. { std::stringstream ss; ss.setstate(std::ios::badbit); @@ -295,6 +327,7 @@ TEST(json, test_stream_writer_errors_and_flags) { EXPECT_FALSE(writer.write(sample).has_value()); EXPECT_FALSE(writer.flush().has_value()); EXPECT_FALSE(writer.finish().has_value()); + EXPECT_FALSE(writer.finish().has_value()); // retry still returns error } { std::stringstream ss; @@ -302,6 +335,18 @@ TEST(json, test_stream_writer_errors_and_flags) { rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::json_array); EXPECT_FALSE(writer.write(sample).has_value()); EXPECT_FALSE(writer.finish().has_value()); + EXPECT_FALSE(writer.finish().has_value()); // retry still returns error + } + + // eofbit alone (without failbit/badbit) does not block writing + { + std::stringstream ss; + ss.setstate(std::ios::eofbit); + rfl::json::StreamWriter writer(ss, rfl::json::StreamFormat::ndjson); + EXPECT_TRUE(writer.write(sample).has_value()); + EXPECT_TRUE(writer.finish().has_value()); + EXPECT_TRUE(writer.flush().has_value()); + EXPECT_NE(ss.str().find("\"Alice\""), std::string::npos); } // Serialization failure (e.g. NaN without ALLOW_INF_AND_NAN) returns Error @@ -858,4 +903,240 @@ TEST(json, test_stream_error_handling) { EXPECT_EQ(collect_ok(trailing), (std::vector{1, 2})); } +TEST(json, test_stream_eof_after_compaction_regression) { + // Blocker #1 repro: default chunk_size, no trailing '\n' on last record. + { + std::istringstream in("{\"id\":1}\n{\"id\":22}"); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + EXPECT_EQ(collect_ok(reader), (std::vector{{1}, {22}})); + } + + // Primitive at EOF after compaction (forces refill_raw -> compact_buffer -> EOF). + { + std::istringstream in("11111111\n22"); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + EXPECT_EQ(collect_ok(reader), (std::vector{11111111, 22})); + } + + // Truncated record at EOF after compaction. + { + std::istringstream in("{\"id\":1}\n{\"id\":22"); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, (IdOnly{1})); + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value()); + EXPECT_FALSE(r2->has_value()); + EXPECT_FALSE(reader.next().has_value()); + } +} + +TEST(json, test_stream_exact_max_record_bytes_crlf) { + // Blocker #3 repro: exact-size record (8 bytes) followed by \r\n. + const std::string crlf_objs = "{\"id\":1}\r\n{\"id\":2}\r\n"; + const std::string crlf_seq = "\x1e{\"id\":1}\r\n\x1e{\"id\":2}\r\n"; + const std::string crlf_arr = "[{\"id\":1}\r\n,{\"id\":2}\r\n]"; + const std::vector expected_ids{{1}, {2}}; + + for (const size_t chunk : + {size_t{1}, size_t{3}, size_t{8}, size_t{9}, size_t{65536}}) { + { + std::istringstream in(crlf_objs); + rfl::json::StreamReader reader( + in, rfl::json::StreamFormat::ndjson, 0, chunk, 8); + EXPECT_EQ(collect_ok(reader), expected_ids) << "ndjson chunk=" << chunk; + } + { + std::istringstream in(crlf_seq); + rfl::json::StreamReader reader( + in, rfl::json::StreamFormat::json_seq, 0, chunk, 8); + EXPECT_EQ(collect_ok(reader), expected_ids) << "json_seq chunk=" << chunk; + } + { + std::istringstream in(crlf_arr); + rfl::json::StreamReader reader( + in, rfl::json::StreamFormat::json_array, 0, chunk, 8); + EXPECT_EQ(collect_ok(reader), expected_ids) + << "json_array chunk=" << chunk; + } + } + + // Exact-size string ("abcdef" = 8 bytes) and primitive (12345678 = 8 bytes) + \r\n + for (const size_t chunk : {size_t{1}, size_t{8}, size_t{65536}}) { + { + std::istringstream in("\"abcdef\"\r\n\"ghijkl\"\r\n"); + rfl::json::StreamReader reader( + in, rfl::json::StreamFormat::ndjson, 0, chunk, 8); + EXPECT_EQ(collect_ok(reader), + (std::vector{"abcdef", "ghijkl"})); + } + { + std::istringstream in("12345678\r\n87654321\r\n"); + rfl::json::StreamReader reader( + in, rfl::json::StreamFormat::ndjson, 0, chunk, 8); + EXPECT_EQ(collect_ok(reader), (std::vector{12345678, 87654321})); + } + } + + // string_view overload with exact-size record + \r\n + { + rfl::json::StreamReader reader( + std::string_view{crlf_objs}, rfl::json::StreamFormat::ndjson, 0, 8); + EXPECT_EQ(collect_ok(reader), expected_ids); + } + + // 1 byte over cap (max_record_bytes = 7 on 8-byte record) must fail + { + std::istringstream in(crlf_objs); + rfl::json::StreamReader reader( + in, rfl::json::StreamFormat::ndjson, 0, 65536, 7); + const auto r = reader.next(); + ASSERT_TRUE(r.has_value()); + EXPECT_FALSE(r->has_value()); + EXPECT_FALSE(reader.next().has_value()); + } + { + std::istringstream in("12345678\r\n"); + rfl::json::StreamReader reader( + in, rfl::json::StreamFormat::ndjson, 0, 65536, 7); + const auto r = reader.next(); + ASSERT_TRUE(r.has_value()); + EXPECT_FALSE(r->has_value()); + EXPECT_FALSE(reader.next().has_value()); + } +} + +TEST(json, test_stream_4kib_chunks_and_unbuffered_linear) { + auto feed_in_chunks = [](ChunkedPipeBuf& _pipe, const std::string& _payload, + const size_t _chunk_bytes) { + for (size_t off = 0; off < _payload.size(); off += _chunk_bytes) { + _pipe.push_chunk(_payload.substr(off, _chunk_bytes)); + } + }; + + auto measure_ms = [](auto&& _fn) { + const auto t0 = std::chrono::steady_clock::now(); + _fn(); + const auto t1 = std::chrono::steady_clock::now(); + return std::chrono::duration_cast(t1 - t0) + .count(); + }; + + // 512 KiB single record fed in 4 KiB chunks (simulates std::ifstream / pipe). + // True O(R) incremental scanner invokes yyjson_read_opts once when record closes. + const Row big_row{99, std::string(512 * 1024, 'q'), 2.75}; + constexpr long long kBudgetMs = 2000; + + for (const auto fmt : + {rfl::json::StreamFormat::ndjson, rfl::json::StreamFormat::json_seq, + rfl::json::StreamFormat::json_array}) { + std::stringstream ss; + { + rfl::json::StreamWriter w(ss, fmt); + ASSERT_TRUE(w.write(big_row).has_value()); + } + const std::string payload = ss.str(); + + ChunkedPipeBuf pipe; + feed_in_chunks(pipe, payload, 4096); + std::istream in(&pipe); + + const auto ms = measure_ms([&] { + rfl::json::StreamReader reader(in, fmt); + const auto res = reader.next(); + ASSERT_TRUE(res.has_value() && res->has_value()) + << (res.has_value() ? res->error().what() : "unexpected eof"); + EXPECT_EQ(**res, big_row); + EXPECT_FALSE(reader.next().has_value()); + }); + EXPECT_LT(ms, kBudgetMs) << "4KiB chunked 512KiB record took " << ms << "ms"; + } + + // Multi-line pretty-printed 256 KiB record in 4 KiB chunks (ndjson) + { + const Row pretty_big{7, std::string(256 * 1024, 'p'), 1.5}; + const std::string payload = + rfl::json::write(pretty_big, rfl::json::pretty) + "\n"; + ChunkedPipeBuf pipe; + feed_in_chunks(pipe, payload, 4096); + std::istream in(&pipe); + + const auto ms = measure_ms([&] { + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + const auto res = reader.next(); + ASSERT_TRUE(res.has_value() && res->has_value()); + EXPECT_EQ(**res, pretty_big); + EXPECT_FALSE(reader.next().has_value()); + }); + EXPECT_LT(ms, kBudgetMs) << "4KiB chunked pretty record took " << ms << "ms"; + } + + // Unbuffered 1-byte-at-a-time stream (in_avail() == 0) in json_array & ndjson + { + const Row med_row{11, std::string(64 * 1024, 'u'), -4.5}; + std::stringstream arr_ss; + { + rfl::json::StreamWriter w(arr_ss, rfl::json::StreamFormat::json_array); + ASSERT_TRUE(w.write(med_row).has_value()); + } + UnbufferedBuf ubuf(arr_ss.str()); + std::istream in(&ubuf); + const auto ms = measure_ms([&] { + rfl::json::StreamReader reader(in, + rfl::json::StreamFormat::json_array); + const auto res = reader.next(); + ASSERT_TRUE(res.has_value() && res->has_value()); + EXPECT_EQ(**res, med_row); + EXPECT_FALSE(reader.next().has_value()); + }); + EXPECT_LT(ms, kBudgetMs) << "unbuffered 64KiB json_array took " << ms << "ms"; + } + + // Non-blocking primitives on live pipe + { + ChunkedPipeBuf pipe; + pipe.push_chunk("123\n"); + pipe.push_chunk("456\n"); + std::istream in(&pipe); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value() && r1->has_value()); + EXPECT_EQ(**r1, 123); + EXPECT_EQ(pipe.underflow_count(), 1u); + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value() && r2->has_value()); + EXPECT_EQ(**r2, 456); + EXPECT_EQ(pipe.underflow_count(), 2u); + } + + // Comments containing braces/quotes inside containers + unclosed brace recovery + { + const std::string with_inner_comments = + "{\n" + " /* } ] \"tricky\" */ \"id\": 1,\n" + " // another } brace and \" quote\n" + " \"name\": \"ok\", \"score\": 1.5\n" + "}\n"; + std::istringstream in(with_inner_comments); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson, + YYJSON_READ_ALLOW_COMMENTS, 7); + EXPECT_EQ(collect_ok(reader), (std::vector{{1, "ok", 1.5}})); + } + { + const std::string unclosed_bad_line = + "{not valid\n" + "{\"id\":2,\"name\":\"recovered\",\"score\":2.5}\n"; + std::istringstream in(unclosed_bad_line); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + const auto r1 = reader.next(); + ASSERT_TRUE(r1.has_value()); + EXPECT_FALSE(r1->has_value()); + const auto r2 = reader.next(); + ASSERT_TRUE(r2.has_value() && r2->has_value()); + EXPECT_EQ(**r2, (Row{2, "recovered", 2.5})); + EXPECT_FALSE(reader.next().has_value()); + } +} + } // namespace test_stream From f744cbc25e68c2fcf4fe1d1ccdbe9e00ab042056 Mon Sep 17 00:00:00 2001 From: clockblocker Date: Fri, 27 Nov 2026 10:54:04 +0100 Subject: [PATCH 4/4] Enforce strict single-line framing in NDJSON and move engine to rfl::internal::json --- include/rfl/json/stream.hpp | 15 ++++--- src/rfl/json/stream.cpp | 78 +++++++++++----------------------- tests/json/test_stream.cpp | 83 ++++++++++++++++++++++++++++--------- 3 files changed, 98 insertions(+), 78 deletions(-) diff --git a/include/rfl/json/stream.hpp b/include/rfl/json/stream.hpp index 65d077747..8aa49f283 100644 --- a/include/rfl/json/stream.hpp +++ b/include/rfl/json/stream.hpp @@ -204,7 +204,11 @@ class StreamWriter { std::optional finish_error_; }; -namespace detail { +} // namespace json + +namespace internal::json { + +using rfl::json::StreamFormat; struct YYJsonDocDeleter { void operator()(yyjson_doc* _doc) const noexcept { yyjson_doc_free(_doc); } @@ -265,8 +269,7 @@ class RFL_API StreamReaderEngine { void advance_past_newline(); void resync_to_rs(); - ScanResult scan_value(bool _line_mode, bool _is_seq, bool _check_first_nl, - std::string* _first_nl_err); + ScanResult scan_value(bool _line_mode, bool _is_seq); std::optional> parse_delimited_value(bool _is_seq); std::optional> parse_array_value(); @@ -290,7 +293,9 @@ class RFL_API StreamReaderEngine { ArrayState array_state_ = ArrayState::before_open; }; -} // namespace detail +} // namespace internal::json + +namespace json { /// Record-level streaming JSON reader. template @@ -375,7 +380,7 @@ class StreamReader { std::default_sentinel_t end() const noexcept { return std::default_sentinel; } private: - detail::StreamReaderEngine engine_; + rfl::internal::json::StreamReaderEngine engine_; std::optional current_; }; diff --git a/src/rfl/json/stream.cpp b/src/rfl/json/stream.cpp index 1c0acbb6f..7c278d657 100644 --- a/src/rfl/json/stream.cpp +++ b/src/rfl/json/stream.cpp @@ -31,7 +31,9 @@ SOFTWARE. #include #include -namespace rfl::json::detail { +namespace rfl::internal::json { + +using rfl::json::StreamFormat; namespace { @@ -461,12 +463,12 @@ void StreamReaderEngine::resync_to_rs() { } StreamReaderEngine::ScanResult StreamReaderEngine::scan_value( - const bool _line_mode, const bool _is_seq, const bool _check_first_nl, - std::string* _first_nl_err) { + const bool _line_mode, const bool _is_seq) { const bool allow_comments = (flag_ & YYJSON_READ_ALLOW_COMMENTS) != 0; const bool allow_single_quote = (flag_ & YYJSON_READ_ALLOW_SINGLE_QUOTED_STR) != 0; const bool allow_ext_escape = (flag_ & YYJSON_READ_ALLOW_EXT_ESCAPE) != 0; + const bool strict_ndjson = _line_mode && !_is_seq; const char c0 = data_ptr()[pos_]; // Case 1: JSON object or array container. @@ -476,7 +478,6 @@ StreamReaderEngine::ScanResult StreamReaderEngine::scan_value( char quote = 0; bool escape = false; CommentMode comment = CommentMode::none; - bool checked_first_nl = !_check_first_nl; size_t refill_step = chunk_size_; while (true) { @@ -508,34 +509,27 @@ StreamReaderEngine::ScanResult StreamReaderEngine::scan_value( comment = CommentMode::none; // Not a comment; fall through to process `c` normally. } else if (comment == CommentMode::line) { + if (strict_ndjson && c == '\n') { + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } ++scan_offset; if (c == '\n' || c == '\r') { comment = CommentMode::none; - if (c == '\n' && !checked_first_nl) { - checked_first_nl = true; - yyjson_read_err err{}; - yyjson_doc* probe = yyjson_read_opts( - const_cast(ptr), scan_offset, - flag_ | YYJSON_READ_STOP_WHEN_DONE, nullptr, &err); - if (probe) { - yyjson_doc_free(probe); - } else if (err.code != YYJSON_READ_ERROR_UNEXPECTED_END && - err.code != YYJSON_READ_ERROR_EMPTY_CONTENT) { - if (_first_nl_err) { - *_first_nl_err = err.msg ? err.msg : "unknown error"; - } - return ScanResult{ScanOutcome::syntax_break, scan_offset}; - } - } } continue; } else if (comment == CommentMode::block) { + if (strict_ndjson && c == '\n') { + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } if (c == '*') { comment = CommentMode::block_star; } ++scan_offset; continue; } else { // CommentMode::block_star + if (strict_ndjson && c == '\n') { + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } if (c == '/') { comment = CommentMode::none; } else if (c != '*') { @@ -563,13 +557,19 @@ StreamReaderEngine::ScanResult StreamReaderEngine::scan_value( continue; } if (!allow_ext_escape && (c == '\n' || c == '\r')) { - ++scan_offset; + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } + if (strict_ndjson && c == '\n') { return ScanResult{ScanOutcome::syntax_break, scan_offset}; } ++scan_offset; continue; } + if (strict_ndjson && c == '\n') { + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } + if (c == '"' || (allow_single_quote && c == '\'')) { quote = c; ++scan_offset; @@ -600,22 +600,6 @@ StreamReaderEngine::ScanResult StreamReaderEngine::scan_value( } ++scan_offset; - if (c == '\n' && !checked_first_nl) { - checked_first_nl = true; - yyjson_read_err err{}; - yyjson_doc* probe = yyjson_read_opts( - const_cast(ptr), scan_offset, - flag_ | YYJSON_READ_STOP_WHEN_DONE, nullptr, &err); - if (probe) { - yyjson_doc_free(probe); - } else if (err.code != YYJSON_READ_ERROR_UNEXPECTED_END && - err.code != YYJSON_READ_ERROR_EMPTY_CONTENT) { - if (_first_nl_err) { - *_first_nl_err = err.msg ? err.msg : "unknown error"; - } - return ScanResult{ScanOutcome::syntax_break, scan_offset}; - } - } } if (max_record_bytes_ > 0 && scan_offset >= max_record_bytes_) { @@ -777,8 +761,7 @@ std::optional> StreamReaderEngine::parse_delimited_value( return std::nullopt; } - std::string first_nl_err; - const ScanResult scan = scan_value(true, _is_seq, !_is_seq, &first_nl_err); + const ScanResult scan = scan_value(true, _is_seq); if (scan.outcome == ScanOutcome::too_large) { return fail("JSON record exceeds maximum allowed size."); @@ -787,19 +770,6 @@ std::optional> StreamReaderEngine::parse_delimited_value( return fail("I/O error while reading JSON stream."); } - if (scan.outcome == ScanOutcome::syntax_break && !first_nl_err.empty()) { - const std::string err_msg = "Could not parse document: " + first_nl_err; - if (_is_seq) { - resync_to_rs(); - } else { - advance_past_newline(); - } - if (io_error_) { - return fail("I/O error while reading JSON stream."); - } - return error(err_msg); - } - if (scan.slice_len == 0) { done_ = true; return std::nullopt; @@ -839,7 +809,7 @@ std::optional> StreamReaderEngine::parse_array_value() { return eof_or_io_error("Could not parse document: unexpected end of data"); } - const ScanResult scan = scan_value(false, false, false, nullptr); + const ScanResult scan = scan_value(false, false); if (scan.outcome == ScanOutcome::too_large) { return fail("JSON record exceeds maximum allowed size."); @@ -977,4 +947,4 @@ std::optional> StreamReaderEngine::next_array_element() { return std::nullopt; } -} // namespace rfl::json::detail +} // namespace rfl::internal::json diff --git a/tests/json/test_stream.cpp b/tests/json/test_stream.cpp index 9440ad45a..c27014756 100644 --- a/tests/json/test_stream.cpp +++ b/tests/json/test_stream.cpp @@ -269,27 +269,17 @@ TEST(json, test_stream_multiline_and_pretty_records) { EXPECT_EQ(collect_ok(reader), expected); } - // StreamReader still supports reading multi-line / pretty-printed ndjson and - // json_seq records (both istream and string_view) + // StreamReader supports multi-line / pretty-printed json_seq records (both + // istream and string_view); ndjson enforces strict single-line framing so + // unclosed records on one line cannot swallow subsequent lines. { - std::string ndjson_pretty; std::string seq_pretty; for (const auto& row : expected) { const auto pretty_rec = rfl::json::write(row, rfl::json::pretty); - ndjson_pretty += pretty_rec + "\n"; seq_pretty += '\x1e'; seq_pretty += pretty_rec + "\n"; } - std::istringstream in_nd(ndjson_pretty); - rfl::json::StreamReader r_nd_in(in_nd, rfl::json::StreamFormat::ndjson, - 0, 13); - EXPECT_EQ(collect_ok(r_nd_in), expected); - - rfl::json::StreamReader r_nd_sv(std::string_view{ndjson_pretty}, - rfl::json::StreamFormat::ndjson); - EXPECT_EQ(collect_ok(r_nd_sv), expected); - std::istringstream in_seq(seq_pretty); rfl::json::StreamReader r_seq_in( in_seq, rfl::json::StreamFormat::json_seq, 0, 13); @@ -1053,17 +1043,19 @@ TEST(json, test_stream_4kib_chunks_and_unbuffered_linear) { EXPECT_LT(ms, kBudgetMs) << "4KiB chunked 512KiB record took " << ms << "ms"; } - // Multi-line pretty-printed 256 KiB record in 4 KiB chunks (ndjson) + // Multi-line pretty-printed 256 KiB record in 4 KiB chunks (json_seq) { const Row pretty_big{7, std::string(256 * 1024, 'p'), 1.5}; const std::string payload = - rfl::json::write(pretty_big, rfl::json::pretty) + "\n"; + std::string("\x1e") + rfl::json::write(pretty_big, rfl::json::pretty) + + "\n"; ChunkedPipeBuf pipe; feed_in_chunks(pipe, payload, 4096); std::istream in(&pipe); const auto ms = measure_ms([&] { - rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + rfl::json::StreamReader reader(in, + rfl::json::StreamFormat::json_seq); const auto res = reader.next(); ASSERT_TRUE(res.has_value() && res->has_value()); EXPECT_EQ(**res, pretty_big); @@ -1110,16 +1102,17 @@ TEST(json, test_stream_4kib_chunks_and_unbuffered_linear) { EXPECT_EQ(pipe.underflow_count(), 2u); } - // Comments containing braces/quotes inside containers + unclosed brace recovery + // Comments containing braces/quotes inside containers (json_seq) + strict + // single-line NDJSON recovery & linear-time DoS resistance { const std::string with_inner_comments = - "{\n" + "\x1e{\n" " /* } ] \"tricky\" */ \"id\": 1,\n" " // another } brace and \" quote\n" " \"name\": \"ok\", \"score\": 1.5\n" "}\n"; std::istringstream in(with_inner_comments); - rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson, + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::json_seq, YYJSON_READ_ALLOW_COMMENTS, 7); EXPECT_EQ(collect_ok(reader), (std::vector{{1, "ok", 1.5}})); } @@ -1137,6 +1130,58 @@ TEST(json, test_stream_4kib_chunks_and_unbuffered_linear) { EXPECT_EQ(**r2, (Row{2, "recovered", 2.5})); EXPECT_FALSE(reader.next().has_value()); } + // Regression: unclosed NDJSON line followed by > max_record_bytes valid lines + // recovers all valid records without hitting fatal max_record_bytes. + { + std::string payload = "{\"id\":0,\n"; + for (int i = 1; i <= 1000; ++i) { + payload += "{\"id\":" + std::to_string(i) + + ",\"name\":\"ok\",\"score\":1.0}\n"; + } + std::istringstream in(payload); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson, 0, + 65536, 4096); + int errs = 0; + int ok = 0; + while (const auto res = reader.next()) { + if (res->has_value()) { + ++ok; + } else { + ++errs; + } + } + EXPECT_EQ(errs, 1); + EXPECT_EQ(ok, 1000); + } + // Regression: 4,000 unclosed "{\n" lines + 4,000 valid records finishes in + // linear time (no O(N^2) rescanning DoS). + { + std::string payload; + payload.reserve(160000); + for (int i = 0; i < 4000; ++i) { + payload += "{\n"; + } + for (int i = 0; i < 4000; ++i) { + payload += "{\"id\":" + std::to_string(i) + + ",\"name\":\"r\",\"score\":1.0}\n"; + } + int errs = 0; + int ok = 0; + const auto ms = measure_ms([&] { + std::istringstream in(payload); + rfl::json::StreamReader reader(in, rfl::json::StreamFormat::ndjson); + while (const auto res = reader.next()) { + if (res->has_value()) { + ++ok; + } else { + ++errs; + } + } + }); + EXPECT_EQ(errs, 4000); + EXPECT_EQ(ok, 4000); + EXPECT_LT(ms, kBudgetMs) << "4000 unclosed NDJSON lines took " << ms << "ms"; + } } } // namespace test_stream