[rpcli] vt.cpp: Add custom non-localized vt_isdigit() and vt_isalpha() functions.

isdigit() is defined as non-localized in C++, but isalpha() is not.

For consistency, define both here. This ensures that *only* the specified
characters are handled as digit or command characters, whereas the
localized versions might accept some other characters.

It's also slightly faster, since it doesn't have to do any localization
checks. Both gcc and MSVC compile vt_isdigit() to a subtract-and-compare.
gcc compiles vt_isalpha() to an AND, subtract, and compare; MSVC ends up
generating a few subtract-and-compares. (clang has the same behavior as
gcc in this case, though the generated code is slightly different.)
This commit is contained in:
David Korth 2025-05-01 20:26:12 -04:00
parent 6213569763
commit ff63ed7ec9

View File

@ -353,6 +353,27 @@ int win32_write_to_console(const ConsoleInfo_t *ci, const char *str, int len)
return 0;
}
/**
* Non-localized isdigit() implementation for ANSI escape sequence processing.
* @param c Character
* @param True if c is a digit; false if not.
*/
static constexpr inline bool vt_isdigit(char c)
{
return ((uint8_t)c >= '0' && (uint8_t)c <= '9');
}
/**
* Non-localized isalpha() implementation for ANSI escape sequence processing.
* @param c Character
* @param True if c is a letter; false if not.
*/
static constexpr inline bool vt_isalpha(char c)
{
return ((uint8_t)c >= 'A' && (uint8_t)c <= 'Z') ||
((uint8_t)c >= 'a' && (uint8_t)c <= 'z');
}
/**
* Write text with ANSI escape sequences to the Windows console. (stdout)
* Color escapes will be handled using SetConsoleTextAttribute().
@ -454,7 +475,7 @@ int win32_console_print_ansi_color(const char *str)
params.push_back(num);
}
num = -1;
} else if (isdigit(c)) {
} else if (vt_isdigit(c)) {
// Found a digit.
// This is part of a parameter.
if (num < 0) {
@ -462,7 +483,7 @@ int win32_console_print_ansi_color(const char *str)
}
num *= 10;
num += (c - '0');
} else if (isalpha(c)) {
} else if (vt_isalpha(c)) {
// Found a letter.
// Finished processing this sequence.
if (num >= 0) {