Add error messages String::hex_to_int functions, and accept capital X in prefix

Co-authored-by: Rémi Verschelde <rverschelde@gmail.com>
This commit is contained in:
Wilson E. Alvarez 2021-10-21 12:31:45 -04:00 committed by Relintai
parent 8fb683fe5d
commit 71fe78538f

View File

@ -1721,9 +1721,7 @@ String::String(const StrRange &p_range) {
int String::hex_to_int(bool p_with_prefix) const {
int len = length();
if (len == 0 || (p_with_prefix && len < 3)) {
return 0;
}
ERR_FAIL_COND_V_MSG(p_with_prefix ? len < 3 : len == 0, 0, String("Invalid hexadecimal notation length in string ") + (p_with_prefix ? "with" : "without") + " prefix \"" + *this + "\".");
const CharType *s = ptr();
@ -1734,9 +1732,7 @@ int String::hex_to_int(bool p_with_prefix) const {
}
if (p_with_prefix) {
if (s[0] != '0' || s[1] != 'x') {
return 0;
}
ERR_FAIL_COND_V_MSG(s[0] != '0' || LOWERCASE(s[1]) != 'x', 0, "Invalid hexadecimal notation prefix in string \"" + *this + "\".");
s += 2;
}
@ -1750,7 +1746,7 @@ int String::hex_to_int(bool p_with_prefix) const {
} else if (c >= 'a' && c <= 'f') {
n = (c - 'a') + 10;
} else {
return 0;
ERR_FAIL_V_MSG(0, "Invalid hexadecimal notation character \"" + chr(*s) + "\" in string \"" + *this + "\".");
}
// Check for overflow/underflow, with special case to ensure INT32_MIN does not result in error
bool overflow = ((hex > INT32_MAX / 16) && (sign == 1 || (sign == -1 && hex != (INT32_MAX >> 4) + 1))) || (sign == -1 && hex == (INT32_MAX >> 4) + 1 && c > '0');
@ -1764,9 +1760,8 @@ int String::hex_to_int(bool p_with_prefix) const {
}
int64_t String::hex_to_int64(bool p_with_prefix) const {
if (p_with_prefix && length() < 3) {
return 0;
}
int len = length();
ERR_FAIL_COND_V_MSG(p_with_prefix ? len < 3 : len == 0, 0, String("Invalid hexadecimal notation length in string ") + (p_with_prefix ? "with" : "without") + " prefix \"" + *this + "\".");
const CharType *s = ptr();
@ -1777,9 +1772,7 @@ int64_t String::hex_to_int64(bool p_with_prefix) const {
}
if (p_with_prefix) {
if (s[0] != '0' || s[1] != 'x') {
return 0;
}
ERR_FAIL_COND_V_MSG(s[0] != '0' || LOWERCASE(s[1]) != 'x', 0, "Invalid hexadecimal notation prefix in string \"" + *this + "\".");
s += 2;
}
@ -1793,7 +1786,7 @@ int64_t String::hex_to_int64(bool p_with_prefix) const {
} else if (c >= 'a' && c <= 'f') {
n = (c - 'a') + 10;
} else {
return 0;
ERR_FAIL_V_MSG(0, "Invalid hexadecimal notation character \"" + chr(*s) + "\" in string \"" + *this + "\".");
}
bool overflow = ((hex > INT64_MAX / 16) && (sign == 1 || (sign == -1 && hex != (INT64_MAX >> 4) + 1))) || (sign == -1 && hex == (INT64_MAX >> 4) + 1 && c > '0');
ERR_FAIL_COND_V_MSG(overflow, sign == 1 ? INT64_MAX : INT64_MIN, "Cannot represent " + *this + " as a 64-bit signed integer, since the value is " + (sign == 1 ? "too large." : "too small."));