Skip to content

Commit

Permalink
node/convert: support conversion for std::string_view (jbeder#1148)
Browse files Browse the repository at this point in the history
  • Loading branch information
tchaikov committed Jul 24, 2023
1 parent b888265 commit 35b4498
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
18 changes: 18 additions & 0 deletions include/yaml-cpp/node/convert.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
#include <valarray>
#include <vector>

#if __cplusplus >= 201703L
#include <string_view>
#endif

#include "yaml-cpp/binary.h"
#include "yaml-cpp/node/impl.h"
#include "yaml-cpp/node/iterator.h"
Expand Down Expand Up @@ -89,6 +93,20 @@ struct convert<char[N]> {
static Node encode(const char* rhs) { return Node(rhs); }
};

#if __cplusplus >= 201703L
template <>
struct convert<std::string_view> {
static Node encode(std::string_view rhs) { return Node(std::string(rhs)); }

static bool decode(const Node& node, std::string_view& rhs) {
if (!node.IsScalar())
return false;
rhs = node.Scalar();
return true;
}
};
#endif

template <>
struct convert<_Null> {
static Node encode(const _Null& /* rhs */) { return Node(); }
Expand Down
9 changes: 9 additions & 0 deletions test/node/node_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,15 @@ TEST(NodeTest, ConstInteratorOnSequence) {
EXPECT_EQ(3, count);
}

#if __cplusplus >= 201703L
TEST(NodeTest, StdStringViewAsKey) {
Node node;
std::string_view key = "username";
node[key] = "monkey";
EXPECT_EQ("monkey", node[key].as<std::string>());
}
#endif

TEST(NodeTest, SimpleSubkeys) {
Node node;
node["device"]["udid"] = "12345";
Expand Down

0 comments on commit 35b4498

Please sign in to comment.