diff --git a/CHANGELOG.md b/CHANGELOG.md index b4beb536..f20e1a4e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,32 @@ ArduinoJson: change log ======================= +HEAD +---- + +* Fixed invalid result from `operator|` (issue #981) + +> ### BREAKING CHANGE +> +> This version slightly changes the behavior of the | operator when the +> variant contains a float and the user requests an integer. +> +> Older versions returned the floating point value truncated. +> Now, it returns the default value. +> +> ```c++ +> // suppose variant contains 1.2 +> int value = variant | 3; +> +> // old behavior: +> value == 1 +> +> // new behavior +> value == 3 +> ``` +> +> If you need the old behavior, you must add `if (variant.is())`. + v6.10.1 (2019-04-23) ------- diff --git a/src/ArduinoJson/Operators/VariantOr.hpp b/src/ArduinoJson/Operators/VariantOr.hpp index 36ad22c4..f43a9b17 100644 --- a/src/ArduinoJson/Operators/VariantOr.hpp +++ b/src/ArduinoJson/Operators/VariantOr.hpp @@ -15,8 +15,7 @@ class VariantOr { public: // Returns the default value if the VariantRef is undefined of incompatible template - typename enable_if::value, T>::type operator|( - const T &defaultValue) const { + T operator|(const T &defaultValue) const { if (impl()->template is()) return impl()->template as(); else @@ -30,17 +29,6 @@ class VariantOr { return value ? value : defaultValue; } - // Returns the default value if the VariantRef is undefined of incompatible - // Special case for integers: we also accept double - template - typename enable_if::value, Integer>::type operator|( - const Integer &defaultValue) const { - if (impl()->template is()) - return impl()->template as(); - else - return defaultValue; - } - private: const TImpl *impl() const { return static_cast(this); diff --git a/test/JsonVariant/or.cpp b/test/JsonVariant/or.cpp index 5dab392c..a703485b 100644 --- a/test/JsonVariant/or.cpp +++ b/test/JsonVariant/or.cpp @@ -51,6 +51,12 @@ TEST_CASE("JsonVariant::operator|()") { REQUIRE(result == "default"); } + SECTION("int | uint8_t (out of range)") { + variant.set(666); + uint8_t result = variant | static_cast(42); + REQUIRE(result == 42); + } + SECTION("int | int") { variant.set(0); int result = variant | 666; @@ -58,8 +64,9 @@ TEST_CASE("JsonVariant::operator|()") { } SECTION("double | int") { - variant.set(42.0); - int result = variant | 666; + // NOTE: changed the behavior to fix #981 + variant.set(666.0); + int result = variant | 42; REQUIRE(result == 42); }