Improve error messages when using char or char*

See #2043
Ported from 650d537b5d
This commit is contained in:
Benoit Blanchon
2024-01-26 18:45:12 +01:00
parent 40ee05c065
commit 0e7262a77b
4 changed files with 29 additions and 13 deletions

View File

@ -1,6 +1,11 @@
ArduinoJson: change log
=======================
HEAD
----
* Improve error messages when using `char` or `char*` (issue #2043)
v6.21.5 (2024-01-10)
-------

View File

@ -154,15 +154,18 @@ TEST_CASE("ConverterNeedsWriteableRef") {
}
namespace ArduinoJson {
void convertToJson(char c, JsonVariant var) {
char buf[] = {c, 0};
var.set(buf);
}
template <>
struct Converter<char> {
static void toJson(char c, JsonVariant var) {
char buf[] = {c, 0};
var.set(buf);
}
void convertFromJson(JsonVariantConst src, char& dst) {
auto p = src.as<const char*>();
dst = p ? p[0] : 0;
}
static char fromJson(JsonVariantConst src) {
auto p = src.as<const char*>();
return p ? p[0] : 0;
}
};
} // namespace ArduinoJson
TEST_CASE("Convert char to string") { // issue #1922

View File

@ -20,6 +20,10 @@ ARDUINOJSON_BEGIN_PUBLIC_NAMESPACE
template <typename T, typename Enable>
struct Converter {
static_assert(!detail::is_same<T, char>::value,
"type 'char' is not supported, use 'signed char', 'unsigned "
"char' or another integer type instead");
static void toJson(const T& src, JsonVariant dst) {
// clang-format off
convertToJson(src, dst); // Error here? See https://arduinojson.org/v6/unsupported-set/
@ -27,6 +31,9 @@ struct Converter {
}
static T fromJson(JsonVariantConst src) {
static_assert(!detail::is_same<T, char*>::value,
"type 'char*' is not supported, use 'const char*' instead");
// clang-format off
T result; // Error here? See https://arduinojson.org/v6/non-default-constructible/
convertFromJson(src, result); // Error here? See https://arduinojson.org/v6/unsupported-as/
@ -35,6 +42,9 @@ struct Converter {
}
static bool checkJson(JsonVariantConst src) {
static_assert(!detail::is_same<T, char*>::value,
"type 'char*' is not supported, use 'const char*' instead");
T dummy = T();
// clang-format off
return canConvertFromJson(src, dummy); // Error here? See https://arduinojson.org/v6/unsupported-is/

View File

@ -95,11 +95,9 @@ class VariantRefBase : public VariantTag {
// Returns true if the value is of the specified type.
// https://arduinojson.org/v6/api/jsonvariant/is/
template <typename T>
FORCE_INLINE typename enable_if<!ConverterNeedsWriteableRef<T>::value &&
!is_same<T, char*>::value &&
!is_same<T, char>::value,
bool>::type
is() const {
FORCE_INLINE
typename enable_if<!ConverterNeedsWriteableRef<T>::value, bool>::type
is() const {
return Converter<T>::checkJson(getVariantConst());
}