Skip to content

Commit 35b4498

Browse files
authored
node/convert: support conversion for std::string_view (#1148)
1 parent b888265 commit 35b4498

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

include/yaml-cpp/node/convert.h

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
#include <valarray>
1919
#include <vector>
2020

21+
#if __cplusplus >= 201703L
22+
#include <string_view>
23+
#endif
24+
2125
#include "yaml-cpp/binary.h"
2226
#include "yaml-cpp/node/impl.h"
2327
#include "yaml-cpp/node/iterator.h"
@@ -89,6 +93,20 @@ struct convert<char[N]> {
8993
static Node encode(const char* rhs) { return Node(rhs); }
9094
};
9195

96+
#if __cplusplus >= 201703L
97+
template <>
98+
struct convert<std::string_view> {
99+
static Node encode(std::string_view rhs) { return Node(std::string(rhs)); }
100+
101+
static bool decode(const Node& node, std::string_view& rhs) {
102+
if (!node.IsScalar())
103+
return false;
104+
rhs = node.Scalar();
105+
return true;
106+
}
107+
};
108+
#endif
109+
92110
template <>
93111
struct convert<_Null> {
94112
static Node encode(const _Null& /* rhs */) { return Node(); }

test/node/node_test.cpp

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,15 @@ TEST(NodeTest, ConstInteratorOnSequence) {
356356
EXPECT_EQ(3, count);
357357
}
358358

359+
#if __cplusplus >= 201703L
360+
TEST(NodeTest, StdStringViewAsKey) {
361+
Node node;
362+
std::string_view key = "username";
363+
node[key] = "monkey";
364+
EXPECT_EQ("monkey", node[key].as<std::string>());
365+
}
366+
#endif
367+
359368
TEST(NodeTest, SimpleSubkeys) {
360369
Node node;
361370
node["device"]["udid"] = "12345";

0 commit comments

Comments
 (0)