From 82d399400edc6104e289e040afe3b7de1016e83a Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 8 Sep 2026 03:44:24 +0200 Subject: [PATCH] [core] Convert a null StringRef to an empty JSON string and pin null against null --- esphome/core/string_ref.h | 2 +- tests/components/core/test_string_ref.cpp | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/esphome/core/string_ref.h b/esphome/core/string_ref.h index 6f15f9da0c..0c4a1d3fa8 100644 --- a/esphome/core/string_ref.h +++ b/esphome/core/string_ref.h @@ -263,7 +263,7 @@ inline double stod(const StringRef &str, size_t *pos = nullptr) { #ifdef USE_JSON // NOLINTNEXTLINE(readability-identifier-naming) -inline void convertToJson(const StringRef &src, JsonVariant dst) { dst.set(src.c_str()); } +inline void convertToJson(const StringRef &src, JsonVariant dst) { dst.set(src.empty() ? "" : src.c_str()); } #endif // USE_JSON } // namespace esphome diff --git a/tests/components/core/test_string_ref.cpp b/tests/components/core/test_string_ref.cpp index 761fe9cb8d..947b738572 100644 --- a/tests/components/core/test_string_ref.cpp +++ b/tests/components/core/test_string_ref.cpp @@ -94,4 +94,12 @@ TEST(StringRefNullEmpty, ComparesAgainstText) { EXPECT_TRUE(text.starts_with(null_empty)); } +TEST(StringRefNullEmpty, TwoNullViewsAreEqual) { + const StringRef a{nullptr, 0}; + const StringRef b{nullptr, 0}; + EXPECT_TRUE(a == b); + EXPECT_EQ(a.compare(b), 0); + EXPECT_TRUE(a.starts_with(b)); +} + } // namespace esphome::core::testing