From 9d58e566fdb32f0b47d56700245126f0b2da8de4 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Tue, 27 Jul 2021 14:15:05 +0200 Subject: [PATCH] Added `as()` and `is()` --- CHANGELOG.md | 1 + extras/tests/Cpp17/string_view.cpp | 14 ++++++++++++++ src/ArduinoJson/Variant/ConverterImpl.hpp | 14 ++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e62fb2fc..6c3485a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ HEAD ---- * Changed return type of `convertToJson()` and `Converter::toJson()` to `void` +* Added `as()` and `is()` v6.18.2 (2021-07-19) ------- diff --git a/extras/tests/Cpp17/string_view.cpp b/extras/tests/Cpp17/string_view.cpp index 3965a50a..56ad48c7 100644 --- a/extras/tests/Cpp17/string_view.cpp +++ b/extras/tests/Cpp17/string_view.cpp @@ -58,6 +58,20 @@ TEST_CASE("string_view") { doc.add(std::string_view("example two", 7)); REQUIRE(doc.memoryUsage() == JSON_ARRAY_SIZE(2) + 8); } + + SECTION("as()") { + doc["s"] = "Hello World"; + doc["i"] = 42; + REQUIRE(doc["s"].as() == std::string_view("Hello World")); + REQUIRE(doc["i"].as() == std::string_view()); + } + + SECTION("is()") { + doc["s"] = "Hello World"; + doc["i"] = 42; + REQUIRE(doc["s"].is() == true); + REQUIRE(doc["i"].is() == false); + } } using ARDUINOJSON_NAMESPACE::adaptString; diff --git a/src/ArduinoJson/Variant/ConverterImpl.hpp b/src/ArduinoJson/Variant/ConverterImpl.hpp index fb9876ed..33f8c650 100644 --- a/src/ArduinoJson/Variant/ConverterImpl.hpp +++ b/src/ArduinoJson/Variant/ConverterImpl.hpp @@ -256,4 +256,18 @@ inline void convertToJson(const ::Printable& src, VariantRef dst) { #endif +#if ARDUINOJSON_ENABLE_STRING_VIEW + +inline void convertFromJson(VariantConstRef src, std::string_view& dst) { + const char* str = src.as(); + if (str) // the standard doesn't allow passing null to the constructor + dst = std::string_view(str); +} + +inline bool canConvertFromJson(VariantConstRef src, const std::string_view&) { + return src.is(); +} + +#endif + } // namespace ARDUINOJSON_NAMESPACE