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 e85d91c39..abdd2a223 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.finish().value(); +writer.flush().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.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..8aa49f283 --- /dev/null +++ b/include/rfl/json/stream.hpp @@ -0,0 +1,390 @@ +#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 +#include + +#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" + +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_), + finish_error_(std::move(_other.finish_error_)) { + _other.stream_ = nullptr; + _other.finished_ = true; + _other.finish_error_.reset(); + } + + StreamWriter& operator=(StreamWriter&&) = delete; + + ~StreamWriter() noexcept { + try { + (void)finish(); + } catch (...) { + } + } + + /// Serializes one record and writes it immediately with framing. + Result write(const auto& _obj) { + if (finished_) { + return error("Cannot write to a finished StreamWriter."); + } + 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_->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; + 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."); + } + if (stream_->eof()) { + stream_->clear(stream_->rdstate() & ~std::ios_base::eofbit); + } + 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; + /// 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_) { + 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) { + if (started_) { + stream_->put(']'); + } else { + stream_->write("[]", 2); + } + } + if (stream_->fail() || stream_->bad()) { + finish_error_ = "I/O error while finishing JSON stream."; + return error(*finish_error_); + } + } catch (const std::exception& _e) { + finish_error_ = + std::string("I/O error while finishing JSON stream: ") + _e.what(); + return error(*finish_error_); + } + return Nothing{}; + } + + private: + std::ostream* stream_; + StreamFormat format_; + yyjson_write_flag flag_; + bool started_ = false; + bool finished_ = false; + std::optional finish_error_; +}; + +} // namespace json + +namespace internal::json { + +using rfl::json::StreamFormat; + +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); + + 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 internal::json + +namespace json { + +/// Record-level streaming JSON reader. +template +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 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_; } + ValueType* operator->() const noexcept { return &(*reader_->current_); } + + 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, + const size_t _max_record_bytes = kDefaultMaxRecordBytes) + : 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) + : engine_(_input, _format, _flag, _max_record_bytes) {} + + 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() { + auto doc_opt = engine_.next_doc(); + if (!doc_opt.has_value()) { + return std::nullopt; + } + if (!doc_opt->has_value()) { + return error(std::move(doc_opt->error())); + } + yyjson_val* root = yyjson_doc_get_root(doc_opt->value().get()); + const auto r = Reader(); + return Parser>::read(r, Reader::InputVarType(root)); + } + + Iterator begin() { + current_ = next(); + return current_.has_value() ? Iterator(this) : Iterator(); + } + + std::default_sentinel_t end() const noexcept { return std::default_sentinel; } + + private: + rfl::internal::json::StreamReaderEngine engine_; + std::optional current_; +}; + +} // namespace json +} // namespace rfl + +#endif 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..7c278d657 --- /dev/null +++ b/src/rfl/json/stream.cpp @@ -0,0 +1,950 @@ +/* + +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::internal::json { + +using rfl::json::StreamFormat; + +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 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. + if (c0 == '{' || c0 == '[') { + size_t scan_offset = 0; + size_t depth = 0; + char quote = 0; + bool escape = false; + CommentMode comment = CommentMode::none; + 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) { + if (strict_ndjson && c == '\n') { + return ScanResult{ScanOutcome::syntax_break, scan_offset}; + } + ++scan_offset; + if (c == '\n' || c == '\r') { + comment = CommentMode::none; + } + 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 != '*') { + 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')) { + 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; + 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 (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; + } + + const ScanResult scan = scan_value(true, _is_seq); + + 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) { + 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); + + 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::internal::json diff --git a/tests/json/test_stream.cpp b/tests/json/test_stream.cpp new file mode 100644 index 000000000..c27014756 --- /dev/null +++ b/tests/json/test_stream.cpp @@ -0,0 +1,1187 @@ +#include + +#include +#include +#include +#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; +}; + +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( + 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) { + 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) { + 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(); + 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) { + ASSERT_TRUE(writer.write(row).has_value()); + } + } + 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) { + 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(); + 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(); + + // StreamWriter allows pretty printing for json_array + { + std::stringstream ss; + { + 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, rfl::json::StreamFormat::json_array, + 0, 13); + EXPECT_EQ(collect_ok(reader), expected); + } + + // 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 seq_pretty; + for (const auto& row : expected) { + const auto pretty_rec = rfl::json::write(row, rfl::json::pretty); + seq_pretty += '\x1e'; + seq_pretty += pretty_rec + "\n"; + } + + 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(), + // and a failed finish() continues returning Error on retry. + { + 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()); + EXPECT_FALSE(writer.finish().has_value()); // retry still returns error + } + { + 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()); + 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 + { + 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) { + 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) { + ASSERT_TRUE(writer.write(s).has_value()); + } + } + + 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) { + ASSERT_TRUE(writer.write(r).has_value()); + } + } + + 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_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) { + 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); + + 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_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 + { + 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})); +} + +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 (json_seq) + { + const Row pretty_big{7, std::string(256 * 1024, 'p'), 1.5}; + const std::string payload = + 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::json_seq); + 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 (json_seq) + strict + // single-line NDJSON recovery & linear-time DoS resistance + { + const std::string with_inner_comments = + "\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::json_seq, + 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()); + } + // 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