From 7c33b3cdab633e59d159d03797017c90ffee8e18 Mon Sep 17 00:00:00 2001 From: Vincent Cogne Date: Mon, 13 Jun 2016 04:59:31 +0200 Subject: [PATCH] Add convert specialization for std::array. --- include/yaml-cpp/node/convert.h | 35 +++++++++++++++++++++++++++++++++ test/node/node_test.cpp | 24 ++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/include/yaml-cpp/node/convert.h b/include/yaml-cpp/node/convert.h index f388a67..f232de7 100644 --- a/include/yaml-cpp/node/convert.h +++ b/include/yaml-cpp/node/convert.h @@ -7,6 +7,7 @@ #pragma once #endif +#include #include #include #include @@ -241,6 +242,40 @@ struct convert > { } }; +// std::array +template +struct convert> { + static Node encode(const std::array& rhs) { + Node node(NodeType::Sequence); + for (const auto& element : rhs) { + node.push_back(element); + } + return node; + } + + static bool decode(const Node& node, std::array& rhs) { + if (!isNodeValid(node)) { + return false; + } + + for (auto i = 0u; i < node.size(); ++i) { +#if defined(__GNUC__) && __GNUC__ < 4 + // workaround for GCC 3: + rhs[i] = node[i].template as(); +#else + rhs[i] = node[i].as(); +#endif + } + return true; + } + +private: + + static bool isNodeValid(const Node& node) { + return node.IsSequence() && node.size() == N; + } +}; + // std::pair template struct convert > { diff --git a/test/node/node_test.cpp b/test/node/node_test.cpp index 4105e72..2202f72 100644 --- a/test/node/node_test.cpp +++ b/test/node/node_test.cpp @@ -12,6 +12,14 @@ using ::testing::AnyOf; using ::testing::Eq; +#define EXPECT_THROW_REPRESENTATION_EXCEPTION(statement, message) \ + ASSERT_THROW(statement, RepresentationException); \ + try { \ + statement; \ + } catch (const RepresentationException& e) { \ + EXPECT_EQ(e.msg, message); \ + } + namespace YAML { namespace { TEST(NodeTest, SimpleScalar) { @@ -154,6 +162,22 @@ TEST(NodeTest, SimpleSubkeys) { EXPECT_EQ("monkey", node["username"].as()); } +TEST(NodeTest, StdArray) { + std::array evens {{ 2, 4, 6, 8, 10 }}; + Node node; + node["evens"] = evens; + std::array actualEvens = node["evens"].as>(); + EXPECT_EQ(evens, actualEvens); +} + +TEST(NodeTest, StdArrayWrongSize) { + std::array evens {{ 2, 4, 6 }}; + Node node; + node["evens"] = evens; + EXPECT_THROW_REPRESENTATION_EXCEPTION((node["evens"].as>()), + ErrorMsg::BAD_CONVERSION); +} + TEST(NodeTest, StdVector) { std::vector primes; primes.push_back(2);