diff --git a/src/json.hpp b/src/json.hpp index 81dc5f8fa46c20907097a624950ca933d00ef9ad..8dfdbb85ed2bb7a531f291cca995c142c2e580f6 100644 --- a/src/json.hpp +++ b/src/json.hpp @@ -7597,6 +7597,12 @@ class basic_json explicit lexer(std::istream& s) : m_stream(&s), m_line_buffer() { + // immediately abort if stream is erroneous + if (s.fail()) + { + throw std::invalid_argument("stream error: " + std::string(strerror(errno))); + } + // fill buffer fill_line_buffer(); diff --git a/src/json.hpp.re2c b/src/json.hpp.re2c index 3b2c75001973be22d0df96ab974bc4b493e2d3db..c9c1f2e7d3e4b40322203673ce5a8f6aaa66b2c8 100644 --- a/src/json.hpp.re2c +++ b/src/json.hpp.re2c @@ -7597,6 +7597,12 @@ class basic_json explicit lexer(std::istream& s) : m_stream(&s), m_line_buffer() { + // immediately abort if stream is erroneous + if (s.fail()) + { + throw std::invalid_argument("stream error: " + std::string(strerror(errno))); + } + // fill buffer fill_line_buffer(); diff --git a/test/src/unit-regression.cpp b/test/src/unit-regression.cpp index cda578abf8c2b4a29f574cf814e0e0fcb36ed448..50cb190fac6d5bbba465bba5f9f9fcecb4e71d59 100644 --- a/test/src/unit-regression.cpp +++ b/test/src/unit-regression.cpp @@ -496,6 +496,12 @@ TEST_CASE("regression tests") CHECK(j == json()); } + SECTION("issue #366 - json::parse on failed stream gets stuck") + { + std::ifstream f("file_not_found.json"); + CHECK_THROWS_AS(json::parse(f), std::invalid_argument); + } + SECTION("issue #367 - calling stream at EOF") { std::stringstream ss;