Skip to content

Commit 524815a

Browse files
authored
Overload parse_yaml to read from std::basic_istream (#1576)
Signed-off-by: Juan Cruz Viotti <jv@jviotti.com>
1 parent 480af56 commit 524815a

File tree

3 files changed

+42
-0
lines changed

3 files changed

+42
-0
lines changed

src/core/yaml/include/sourcemeta/core/yaml.h

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include <sourcemeta/core/json.h>
1111

1212
#include <filesystem> // std::filesystem
13+
#include <istream> // std::basic_istream
1314

1415
/// @defgroup yaml YAML
1516
/// @brief A YAML compatibility library based on `libyaml`.
@@ -22,6 +23,25 @@
2223

2324
namespace sourcemeta::core {
2425

26+
/// @ingroup yaml
27+
///
28+
/// Create a JSON document from a C++ standard input stream that represents a
29+
/// YAML document. For example:
30+
///
31+
/// ```cpp
32+
/// #include <sourcemeta/core/json.h>
33+
/// #include <cassert>
34+
/// #include <sstream>
35+
///
36+
/// std::istringstream stream{"foo: bar"};
37+
/// const sourcemeta::core::JSON document =
38+
/// sourcemeta::core::parse_yaml(stream);
39+
/// assert(document.is_object());
40+
/// ```
41+
SOURCEMETA_CORE_YAML_EXPORT
42+
auto parse_yaml(std::basic_istream<JSON::Char, JSON::CharTraits> &stream)
43+
-> JSON;
44+
2545
/// @ingroup yaml
2646
///
2747
/// Create a JSON document from a C++ standard input stream that represents a

src/core/yaml/yaml.cc

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,13 @@ static auto internal_parse_json(yaml_parser_t *parser)
9191

9292
namespace sourcemeta::core {
9393

94+
auto parse_yaml(std::basic_istream<JSON::Char, JSON::CharTraits> &stream)
95+
-> JSON {
96+
std::basic_ostringstream<JSON::Char, JSON::CharTraits> buffer;
97+
buffer << stream.rdbuf();
98+
return parse_yaml(buffer.str());
99+
}
100+
94101
auto parse_yaml(const JSON::String &input) -> JSON {
95102
yaml_parser_t parser;
96103
if (!yaml_parser_initialize(&parser)) {

test/yaml/yaml_parse_test.cc

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#include <gtest/gtest.h>
22

3+
#include <sstream>
4+
35
#include <sourcemeta/core/json.h>
46
#include <sourcemeta/core/yaml.h>
57

@@ -81,3 +83,16 @@ TEST(YAML_parse, file_not_exists) {
8183
"not_exists.yaml"),
8284
std::filesystem::filesystem_error);
8385
}
86+
87+
TEST(YAML_parse, istringstream) {
88+
std::istringstream stream{"hello: world\nfoo: 1\nbar: true"};
89+
const auto result{sourcemeta::core::parse_yaml(stream)};
90+
91+
const sourcemeta::core::JSON expected = sourcemeta::core::parse_json(R"JSON({
92+
"hello": "world",
93+
"foo": 1,
94+
"bar": true
95+
})JSON");
96+
97+
EXPECT_EQ(result, expected);
98+
}

0 commit comments

Comments
 (0)