diff --git a/extras/tests/Cpp11/CMakeLists.txt b/extras/tests/Cpp11/CMakeLists.txt index 18e54baf..0b84a14c 100644 --- a/extras/tests/Cpp11/CMakeLists.txt +++ b/extras/tests/Cpp11/CMakeLists.txt @@ -15,6 +15,10 @@ if("cxx_long_long_type" IN_LIST CMAKE_CXX_COMPILE_FEATURES) list(APPEND SOURCES use_long_long_0.cpp use_long_long_1.cpp) endif() +if("cxx_range_for" IN_LIST CMAKE_CXX_COMPILE_FEATURES AND "cxx_generalized_initializers" IN_LIST CMAKE_CXX_COMPILE_FEATURES) + list(APPEND SOURCES stl_containers.cpp) +endif() + if(NOT SOURCES) return() endif() @@ -28,5 +32,5 @@ add_test(Cpp11 Cpp11Tests) set_tests_properties(Cpp11 PROPERTIES - LABELS "Catch" + LABELS "Catch" ) diff --git a/extras/tests/Cpp11/stl_containers.cpp b/extras/tests/Cpp11/stl_containers.cpp new file mode 100644 index 00000000..9e590c14 --- /dev/null +++ b/extras/tests/Cpp11/stl_containers.cpp @@ -0,0 +1,72 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2022, Benoit BLANCHON +// MIT License + +#include +#include +#include + +#include +#include + +namespace ARDUINOJSON_NAMESPACE { +template +struct Converter > { + static void toJson(const std::vector& src, JsonVariant dst) { + JsonArray array = dst.to(); + for (T item : src) + array.add(item); + } + + static std::vector fromJson(JsonVariantConst src) { + std::vector dst; + for (T item : src.as()) + dst.push_back(item); + return dst; + } + + static bool checkJson(JsonVariantConst src) { + JsonArrayConst array = src; + bool result = array; + for (JsonVariantConst item : array) { + if (!result) + break; + result = item.is(); + } + return result; + } +}; +} // namespace ARDUINOJSON_NAMESPACE + +TEST_CASE("vector") { + SECTION("toJson") { + std::vector v = {1, 2}; + + StaticJsonDocument<128> doc; + doc.set(v); + REQUIRE(doc.as() == "[1,2]"); + } + + SECTION("fromJson") { + StaticJsonDocument<128> doc; + doc.add(1); + doc.add(2); + + auto v = doc.as >(); + REQUIRE(v.size() == 2); + CHECK(v[0] == 1); + CHECK(v[1] == 2); + } + + SECTION("checkJson") { + StaticJsonDocument<128> doc; + CHECK(doc.is >() == false); + + doc.add(1); + doc.add(2); + CHECK(doc.is >() == true); + + doc.add("foo"); + CHECK(doc.is >() == false); + } +}