From f0e84e4933b0d4120cd30ac1e0054ae67319f773 Mon Sep 17 00:00:00 2001 From: Benoit Blanchon Date: Mon, 7 Apr 2025 09:46:02 +0200 Subject: [PATCH] Fix support for `const char[]` Fixes #2166 --- CHANGELOG.md | 1 + extras/tests/Misc/CMakeLists.txt | 1 + extras/tests/Misc/StringAdapters.cpp | 1 + extras/tests/Misc/issue2166.cpp | 22 +++++++++++++++++++ .../Strings/Adapters/RamString.hpp | 10 +++++++++ 5 files changed, 35 insertions(+) create mode 100644 extras/tests/Misc/issue2166.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index ff2d14ab..ccefd7c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ HEAD ---- * Optimize storage of tiny strings (up to 3 characters) +* Fix support for `const char[]` (issue #2166) v7.3.1 (2025-02-27) ------ diff --git a/extras/tests/Misc/CMakeLists.txt b/extras/tests/Misc/CMakeLists.txt index 4edd2ba5..05be1ca8 100644 --- a/extras/tests/Misc/CMakeLists.txt +++ b/extras/tests/Misc/CMakeLists.txt @@ -7,6 +7,7 @@ add_executable(MiscTests conflicts.cpp issue1967.cpp issue2129.cpp + issue2166.cpp JsonString.cpp NoArduinoHeader.cpp printable.cpp diff --git a/extras/tests/Misc/StringAdapters.cpp b/extras/tests/Misc/StringAdapters.cpp index c2ebf1fd..99178975 100644 --- a/extras/tests/Misc/StringAdapters.cpp +++ b/extras/tests/Misc/StringAdapters.cpp @@ -128,6 +128,7 @@ TEST_CASE("IsString") { CHECK(IsString::value == true); CHECK(IsString::value == true); CHECK(IsString::value == true); + CHECK(IsString::value == true); CHECK(IsString<::String>::value == true); CHECK(IsString<::StringSumHelper>::value == true); CHECK(IsString::value == false); diff --git a/extras/tests/Misc/issue2166.cpp b/extras/tests/Misc/issue2166.cpp new file mode 100644 index 00000000..f068bd62 --- /dev/null +++ b/extras/tests/Misc/issue2166.cpp @@ -0,0 +1,22 @@ +// ArduinoJson - https://arduinojson.org +// Copyright © 2014-2025, Benoit BLANCHON +// MIT License + +#include +#include + +struct CCLASS { + static const char mszKey[]; +}; + +TEST_CASE("Issue #2166") { + JsonDocument doc; + doc[CCLASS::mszKey] = 12; + REQUIRE(doc.as() == "{\"test3\":12}"); + + JsonObject obj = doc.to(); + obj[CCLASS::mszKey] = 12; + REQUIRE(doc.as() == "{\"test3\":12}"); +} + +const char CCLASS::mszKey[] = "test3"; diff --git a/src/ArduinoJson/Strings/Adapters/RamString.hpp b/src/ArduinoJson/Strings/Adapters/RamString.hpp index deb09980..c269ffb7 100644 --- a/src/ArduinoJson/Strings/Adapters/RamString.hpp +++ b/src/ArduinoJson/Strings/Adapters/RamString.hpp @@ -76,6 +76,16 @@ struct StringAdapter::value>> { } }; +template +struct StringAdapter::value>> { + using AdaptedString = RamString; + + static AdaptedString adapt(const TChar* p) { + auto str = reinterpret_cast(p); + return AdaptedString(str, str ? ::strlen(str) : 0); + } +}; + template struct StringAdapter { using AdaptedString = RamString;