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
parent 27b63247fd
commit f12a1b6214
No known key found for this signature in database
GPG Key ID: A32174A3D2ED3F9E

View File

@ -1706,9 +1706,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();
@ -1719,9 +1717,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;
}
@ -1735,7 +1731,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');
@ -1749,9 +1745,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();
@ -1762,9 +1757,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;
}
@ -1778,7 +1771,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."));