diff --git a/src/string.cpp b/src/string.cpp --- a/src/string.cpp +++ b/src/string.cpp @@ -185,18 +185,11 @@ void str_fix_scc_encoded(char *str, cons } -/** - * Scans the string for valid characters and if it finds invalid ones, - * replaces them with a question mark '?' (if not ignored) - * @param str the string to validate - * @param last the last valid character of str - * @param settings the settings for the string validation. - */ -void str_validate(char *str, const char *last, StringValidationSettings settings) +template +static void str_validate(T &dst, const char *str, const char *last, StringValidationSettings settings) { /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */ - char *dst = str; while (str <= last && *str != '\0') { size_t len = Utf8EncodedCharLen(*str); /* If the character is unknown, i.e. encoded length is 0 @@ -220,7 +213,7 @@ void str_validate(char *str, const char do { *dst++ = *str++; } while (--len != 0); - } else if ((settings & SVS_ALLOW_NEWLINE) != 0 && c == '\n') { + } else if ((settings & SVS_ALLOW_NEWLINE) != 0 && c == '\n') { *dst++ = *str++; } else { if ((settings & SVS_ALLOW_NEWLINE) != 0 && c == '\r' && str[1] == '\n') { @@ -232,12 +225,42 @@ void str_validate(char *str, const char if ((settings & SVS_REPLACE_WITH_QUESTION_MARK) != 0) *dst++ = '?'; } } +} +/** + * Scans the string for valid characters and if it finds invalid ones, + * replaces them with a question mark '?' (if not ignored) + * @param str the string to validate + * @param last the last valid character of str + * @param settings the settings for the string validation. + */ +void str_validate(char *str, const char *last, StringValidationSettings settings) +{ + char *dst = str; + str_validate(dst, str, last, settings); *dst = '\0'; } /** * Scans the string for valid characters and if it finds invalid ones, + * replaces them with a question mark '?' (if not ignored) + * @param str the string to validate + * @param settings the settings for the string validation. + */ +std::string str_validate(const std::string &str, StringValidationSettings settings) +{ + auto buf = str.data(); + auto last = buf + str.size(); + + std::ostringstream dst; + std::ostreambuf_iterator dst_iter(dst); + str_validate(dst_iter, buf, last, settings); + + return dst.str(); +} + +/** + * Scans the string for valid characters and if it finds invalid ones, * replaces them with a question mark '?'. * @param str the string to validate */