1
0
Fork 0

Codechange: rename str_validate to StrMakeValid(InPlace) (#9304)

This to be more explicit the function changes the value, and not
returns yes/no.
pull/9307/head
Patric Stout 2021-05-29 11:21:38 +02:00 committed by GitHub
parent 4d74e51907
commit ca9a7df752
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 63 additions and 62 deletions

View File

@ -111,7 +111,7 @@ void IConsolePrint(TextColour colour_code, const char *string)
* characters and (when applicable) assign it to the console buffer */ * characters and (when applicable) assign it to the console buffer */
str = stredup(string); str = stredup(string);
str_strip_colours(str); str_strip_colours(str);
str_validate(str, str + strlen(str)); StrMakeValidInPlace(str);
if (_network_dedicated) { if (_network_dedicated) {
NetworkAdminConsole("console", str); NetworkAdminConsole("console", str);

View File

@ -342,7 +342,7 @@ bool FiosFileScanner::AddFile(const std::string &filename, size_t basepath_lengt
t = filename.c_str() + (ps == std::string::npos ? 0 : ps + 1); t = filename.c_str() + (ps == std::string::npos ? 0 : ps + 1);
} }
strecpy(fios->title, t, lastof(fios->title)); strecpy(fios->title, t, lastof(fios->title));
str_validate(fios->title, lastof(fios->title)); StrMakeValidInPlace(fios->title, lastof(fios->title));
return true; return true;
} }
@ -394,7 +394,7 @@ static void FiosGetFileList(SaveLoadOperation fop, fios_getlist_callback_proc *c
std::string dirname = std::string(d_name) + PATHSEP; std::string dirname = std::string(d_name) + PATHSEP;
SetDParamStr(0, dirname); SetDParamStr(0, dirname);
GetString(fios->title, STR_SAVELOAD_DIRECTORY, lastof(fios->title)); GetString(fios->title, STR_SAVELOAD_DIRECTORY, lastof(fios->title));
str_validate(fios->title, lastof(fios->title)); StrMakeValidInPlace(fios->title, lastof(fios->title));
} }
} }
closedir(dir); closedir(dir);
@ -446,7 +446,7 @@ static void GetFileTitle(const std::string &file, char *title, const char *last,
size_t read = fread(title, 1, last - title, f); size_t read = fread(title, 1, last - title, f);
assert(title + read <= last); assert(title + read <= last);
title[read] = '\0'; title[read] = '\0';
str_validate(title, last); StrMakeValidInPlace(title, last);
FioFCloseFile(f); FioFCloseFile(f);
} }

View File

@ -170,7 +170,7 @@ void LoadFromHighScore()
i = SP_SAVED_HIGHSCORE_END; i = SP_SAVED_HIGHSCORE_END;
break; break;
} }
str_validate(hs->company, lastof(hs->company), SVS_NONE); StrMakeValidInPlace(hs->company, lastof(hs->company), SVS_NONE);
hs->title = EndGameGetPerformanceTitleFromValue(hs->score); hs->title = EndGameGetPerformanceTitleFromValue(hs->score);
} }
} }

View File

@ -22,7 +22,7 @@
*/ */
IniItem::IniItem(IniGroup *parent, const std::string &name) : next(nullptr) IniItem::IniItem(IniGroup *parent, const std::string &name) : next(nullptr)
{ {
this->name = str_validate(name); this->name = StrMakeValid(name);
*parent->last_item = this; *parent->last_item = this;
parent->last_item = &this->next; parent->last_item = &this->next;
@ -50,7 +50,7 @@ void IniItem::SetValue(const std::string_view value)
*/ */
IniGroup::IniGroup(IniLoadFile *parent, const std::string &name) : next(nullptr), type(IGT_VARIABLES), item(nullptr) IniGroup::IniGroup(IniLoadFile *parent, const std::string &name) : next(nullptr), type(IGT_VARIABLES), item(nullptr)
{ {
this->name = str_validate(name); this->name = StrMakeValid(name);
this->last_item = &this->item; this->last_item = &this->item;
*parent->last_group = this; *parent->last_group = this;
@ -288,7 +288,7 @@ void IniLoadFile::LoadFromDisk(const std::string &filename, Subdirectory subdir)
if (!quoted && e == t) { if (!quoted && e == t) {
item->value.reset(); item->value.reset();
} else { } else {
item->value = str_validate(std::string(t)); item->value = StrMakeValid(std::string(t));
} }
} else { } else {
/* it's an orphan item */ /* it's an orphan item */

View File

@ -997,7 +997,7 @@ struct QueryStringWindow : public Window
{ {
char *last_of = &this->editbox.text.buf[this->editbox.text.max_bytes - 1]; char *last_of = &this->editbox.text.buf[this->editbox.text.max_bytes - 1];
GetString(this->editbox.text.buf, str, last_of); GetString(this->editbox.text.buf, str, last_of);
str_validate(this->editbox.text.buf, last_of, SVS_NONE); StrMakeValidInPlace(this->editbox.text.buf, last_of, SVS_NONE);
/* Make sure the name isn't too long for the text buffer in the number of /* Make sure the name isn't too long for the text buffer in the number of
* characters (not bytes). max_chars also counts the '\0' characters. */ * characters (not bytes). max_chars also counts the '\0' characters. */

View File

@ -394,7 +394,7 @@ void Packet::Recv_string(char *buffer, size_t size, StringValidationSettings set
assert(pos <= std::numeric_limits<PacketSize>::max()); assert(pos <= std::numeric_limits<PacketSize>::max());
this->pos = static_cast<PacketSize>(pos); this->pos = static_cast<PacketSize>(pos);
str_validate(bufp, last, settings); StrMakeValidInPlace(bufp, last, settings);
} }
/** /**
@ -423,7 +423,7 @@ std::string Packet::Recv_string(size_t length, StringValidationSettings settings
while (this->Recv_uint8() != '\0') {} while (this->Recv_uint8() != '\0') {}
} }
return str_validate(str, settings); return StrMakeValid(str, settings);
} }
/** /**

View File

@ -2598,7 +2598,7 @@ static std::string ReadDWordAsString(ByteReader *reader)
char output[5]; char output[5];
for (int i = 0; i < 4; i++) output[i] = reader->ReadByte(); for (int i = 0; i < 4; i++) output[i] = reader->ReadByte();
output[4] = '\0'; output[4] = '\0';
str_validate(output, lastof(output)); StrMakeValidInPlace(output, lastof(output));
return std::string(output); return std::string(output);
} }

View File

@ -174,7 +174,7 @@ int CDECL main(int argc, char *argv[])
SetRandomSeed(time(nullptr)); SetRandomSeed(time(nullptr));
/* Make sure our arguments contain only valid UTF-8 characters. */ /* Make sure our arguments contain only valid UTF-8 characters. */
for (int i = 0; i < argc; i++) ValidateString(argv[i]); for (int i = 0; i < argc; i++) StrMakeValidInPlace(argv[i]);
return openttd_main(argc, argv); return openttd_main(argc, argv);
} }

View File

@ -243,7 +243,7 @@ void CocoaReleaseAutoreleasePool();
int CDECL main(int argc, char *argv[]) int CDECL main(int argc, char *argv[])
{ {
/* Make sure our arguments contain only valid UTF-8 characters. */ /* Make sure our arguments contain only valid UTF-8 characters. */
for (int i = 0; i < argc; i++) ValidateString(argv[i]); for (int i = 0; i < argc; i++) StrMakeValidInPlace(argv[i]);
#ifdef WITH_COCOA #ifdef WITH_COCOA
CocoaSetupAutoreleasePool(); CocoaSetupAutoreleasePool();

View File

@ -429,7 +429,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLi
argc = ParseCommandLine(cmdline, argv, lengthof(argv)); argc = ParseCommandLine(cmdline, argv, lengthof(argv));
/* Make sure our arguments contain only valid UTF-8 characters. */ /* Make sure our arguments contain only valid UTF-8 characters. */
for (int i = 0; i < argc; i++) ValidateString(argv[i]); for (int i = 0; i < argc; i++) StrMakeValidInPlace(argv[i]);
openttd_main(argc, argv); openttd_main(argc, argv);

View File

@ -234,7 +234,7 @@ static inline bool CheckOldSavegameType(FILE *f, char *temp, const char *last, u
bool ret = VerifyOldNameChecksum(temp, len); bool ret = VerifyOldNameChecksum(temp, len);
temp[len - 2] = '\0'; // name is null-terminated in savegame, but it's better to be sure temp[len - 2] = '\0'; // name is null-terminated in savegame, but it's better to be sure
str_validate(temp, last); StrMakeValidInPlace(temp, last);
return ret; return ret;
} }

View File

@ -972,7 +972,7 @@ static void SlString(void *ptr, size_t length, VarType conv)
if ((conv & SLF_ALLOW_NEWLINE) != 0) { if ((conv & SLF_ALLOW_NEWLINE) != 0) {
settings = settings | SVS_ALLOW_NEWLINE; settings = settings | SVS_ALLOW_NEWLINE;
} }
str_validate((char *)ptr, (char *)ptr + len, settings); StrMakeValidInPlace((char *)ptr, (char *)ptr + len, settings);
break; break;
} }
case SLA_PTRS: break; case SLA_PTRS: break;
@ -1016,7 +1016,7 @@ static void SlStdString(void *ptr, VarType conv)
if ((conv & SLF_ALLOW_NEWLINE) != 0) { if ((conv & SLF_ALLOW_NEWLINE) != 0) {
settings = settings | SVS_ALLOW_NEWLINE; settings = settings | SVS_ALLOW_NEWLINE;
} }
str_validate(buf, buf + len, settings); StrMakeValidInPlace(buf, buf + len, settings);
// Store sanitized string. // Store sanitized string.
str->assign(buf); str->assign(buf);

View File

@ -283,7 +283,7 @@ ScriptObject::ActiveInstance::~ActiveInstance()
{ {
char buffer[64]; char buffer[64];
::GetString(buffer, string, lastof(buffer)); ::GetString(buffer, string, lastof(buffer));
::str_validate(buffer, lastof(buffer), SVS_NONE); ::StrMakeValidInPlace(buffer, lastof(buffer), SVS_NONE);
return ::stredup(buffer); return ::stredup(buffer);
} }
@ -312,7 +312,7 @@ ScriptObject::ActiveInstance::~ActiveInstance()
if (!StrEmpty(text) && (GetCommandFlags(cmd) & CMD_STR_CTRL) == 0) { if (!StrEmpty(text) && (GetCommandFlags(cmd) & CMD_STR_CTRL) == 0) {
/* The string must be valid, i.e. not contain special codes. Since some /* The string must be valid, i.e. not contain special codes. Since some
* can be made with GSText, make sure the control codes are removed. */ * can be made with GSText, make sure the control codes are removed. */
::str_validate(const_cast<char *>(text), text + strlen(text), SVS_NONE); ::StrMakeValidInPlace(text, SVS_NONE);
} }
/* Set the default callback to return a true/false result of the DoCommand */ /* Set the default callback to return a true/false result of the DoCommand */

View File

@ -82,7 +82,7 @@ SQInteger ScriptText::_SetParam(int parameter, HSQUIRRELVM vm)
sq_getstring(vm, -1, &value); sq_getstring(vm, -1, &value);
this->params[parameter] = stredup(value); this->params[parameter] = stredup(value);
ValidateString(this->params[parameter]); StrMakeValidInPlace(this->params[parameter]);
break; break;
} }
@ -157,7 +157,7 @@ SQInteger ScriptText::_set(HSQUIRRELVM vm)
if (sq_gettype(vm, 2) == OT_STRING) { if (sq_gettype(vm, 2) == OT_STRING) {
const SQChar *key_string; const SQChar *key_string;
sq_getstring(vm, 2, &key_string); sq_getstring(vm, 2, &key_string);
ValidateString(key_string); StrMakeValidInPlace(key_string);
if (strncmp(key_string, "param_", 6) != 0 || strlen(key_string) > 8) return SQ_ERROR; if (strncmp(key_string, "param_", 6) != 0 || strlen(key_string) > 8) return SQ_ERROR;
k = atoi(key_string + 6); k = atoi(key_string + 6);

View File

@ -122,14 +122,14 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm)
while (SQ_SUCCEEDED(sq_next(vm, -2))) { while (SQ_SUCCEEDED(sq_next(vm, -2))) {
const SQChar *key; const SQChar *key;
if (SQ_FAILED(sq_getstring(vm, -2, &key))) return SQ_ERROR; if (SQ_FAILED(sq_getstring(vm, -2, &key))) return SQ_ERROR;
ValidateString(key); StrMakeValidInPlace(key);
if (strcmp(key, "name") == 0) { if (strcmp(key, "name") == 0) {
const SQChar *sqvalue; const SQChar *sqvalue;
if (SQ_FAILED(sq_getstring(vm, -1, &sqvalue))) return SQ_ERROR; if (SQ_FAILED(sq_getstring(vm, -1, &sqvalue))) return SQ_ERROR;
char *name = stredup(sqvalue); char *name = stredup(sqvalue);
char *s; char *s;
ValidateString(name); StrMakeValidInPlace(name);
/* Don't allow '=' and ',' in configure setting names, as we need those /* Don't allow '=' and ',' in configure setting names, as we need those
* 2 chars to nicely store the settings as a string. */ * 2 chars to nicely store the settings as a string. */
@ -141,7 +141,7 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm)
const SQChar *sqdescription; const SQChar *sqdescription;
if (SQ_FAILED(sq_getstring(vm, -1, &sqdescription))) return SQ_ERROR; if (SQ_FAILED(sq_getstring(vm, -1, &sqdescription))) return SQ_ERROR;
config.description = stredup(sqdescription); config.description = stredup(sqdescription);
ValidateString(config.description); StrMakeValidInPlace(config.description);
items |= 0x002; items |= 0x002;
} else if (strcmp(key, "min_value") == 0) { } else if (strcmp(key, "min_value") == 0) {
SQInteger res; SQInteger res;
@ -226,7 +226,7 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm)
{ {
const SQChar *setting_name; const SQChar *setting_name;
if (SQ_FAILED(sq_getstring(vm, -2, &setting_name))) return SQ_ERROR; if (SQ_FAILED(sq_getstring(vm, -2, &setting_name))) return SQ_ERROR;
ValidateString(setting_name); StrMakeValidInPlace(setting_name);
ScriptConfigItem *config = nullptr; ScriptConfigItem *config = nullptr;
for (auto &item : this->config_list) { for (auto &item : this->config_list) {
@ -253,7 +253,7 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm)
/* Because squirrel doesn't support identifiers starting with a digit, /* Because squirrel doesn't support identifiers starting with a digit,
* we skip the first character. */ * we skip the first character. */
int key = atoi(key_string + 1); int key = atoi(key_string + 1);
ValidateString(label); StrMakeValidInPlace(label);
/* !Contains() prevents stredup from leaking. */ /* !Contains() prevents stredup from leaking. */
if (!config->labels->Contains(key)) config->labels->Insert(key, stredup(label)); if (!config->labels->Contains(key)) config->labels->Insert(key, stredup(label));

View File

@ -448,7 +448,7 @@ bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_nam
if (!this->CallMethod(instance, method_name, &ret, suspend)) return false; if (!this->CallMethod(instance, method_name, &ret, suspend)) return false;
if (ret._type != OT_STRING) return false; if (ret._type != OT_STRING) return false;
*res = stredup(ObjectToString(&ret)); *res = stredup(ObjectToString(&ret));
ValidateString(*res); StrMakeValidInPlace(*res);
return true; return true;
} }

View File

@ -116,7 +116,7 @@ namespace SQConvert {
char *tmp_str = stredup(tmp); char *tmp_str = stredup(tmp);
sq_poptop(vm); sq_poptop(vm);
ptr->push_back((void *)tmp_str); ptr->push_back((void *)tmp_str);
str_validate(tmp_str, tmp_str + strlen(tmp_str)); StrMakeValidInPlace(tmp_str);
return tmp_str; return tmp_str;
} }

View File

@ -497,7 +497,7 @@ void StringSettingDesc::MakeValueValid(std::string &str) const
* includes the '\0' termination for network transfer purposes. * includes the '\0' termination for network transfer purposes.
* Also ensure the string is valid after chopping of some bytes. */ * Also ensure the string is valid after chopping of some bytes. */
std::string stdstr(str, this->max_length - 1); std::string stdstr(str, this->max_length - 1);
str.assign(str_validate(stdstr, SVS_NONE)); str.assign(StrMakeValid(stdstr, SVS_NONE));
} }
/** /**

View File

@ -186,7 +186,7 @@ void str_fix_scc_encoded(char *str, const char *last)
template <class T> template <class T>
static void str_validate(T &dst, const char *str, const char *last, StringValidationSettings settings) static void StrMakeValidInPlace(T &dst, const char *str, const char *last, StringValidationSettings settings)
{ {
/* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */ /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */
@ -246,49 +246,50 @@ static void str_validate(T &dst, const char *str, const char *last, StringValida
} }
/** /**
* Scans the string for valid characters and if it finds invalid ones, * Scans the string for invalid characters and replaces then with a
* replaces them with a question mark '?' (if not ignored) * question mark '?' (if not ignored).
* @param str the string to validate * @param str The string to validate.
* @param last the last valid character of str * @param last The last valid character of str.
* @param settings the settings for the string validation. * @param settings The settings for the string validation.
*/ */
void str_validate(char *str, const char *last, StringValidationSettings settings) void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings)
{ {
char *dst = str; char *dst = str;
str_validate(dst, str, last, settings); StrMakeValidInPlace(dst, str, last, settings);
*dst = '\0'; *dst = '\0';
} }
/** /**
* Scans the string for valid characters and if it finds invalid ones, * Scans the string for invalid characters and replaces then with a
* replaces them with a question mark '?' (if not ignored) * question mark '?' (if not ignored).
* @param str the string to validate * Only use this function when you are sure the string ends with a '\0';
* @param settings the settings for the string validation. * otherwise use StrMakeValidInPlace(str, last, settings) variant.
* @param str The string (of which you are sure ends with '\0') to validate.
*/ */
std::string str_validate(const std::string &str, StringValidationSettings settings) void StrMakeValidInPlace(const char *str, StringValidationSettings settings)
{
/* We know it is '\0' terminated. */
StrMakeValidInPlace(const_cast<char *>(str), str + strlen(str), settings);
}
/**
* Scans the string for invalid characters and replaces then with a
* question mark '?' (if not ignored).
* @param str The string to validate.
* @param settings The settings for the string validation.
*/
std::string StrMakeValid(const std::string &str, StringValidationSettings settings)
{ {
auto buf = str.data(); auto buf = str.data();
auto last = buf + str.size(); auto last = buf + str.size();
std::ostringstream dst; std::ostringstream dst;
std::ostreambuf_iterator<char> dst_iter(dst); std::ostreambuf_iterator<char> dst_iter(dst);
str_validate(dst_iter, buf, last, settings); StrMakeValidInPlace(dst_iter, buf, last, settings);
return dst.str(); 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
*/
void ValidateString(const char *str)
{
/* We know it is '\0' terminated. */
str_validate(const_cast<char *>(str), str + strlen(str) + 1);
}
/** /**
* Checks whether the given string is valid, i.e. contains only * Checks whether the given string is valid, i.e. contains only
* valid (printable) characters and is properly terminated. * valid (printable) characters and is properly terminated.

View File

@ -39,9 +39,9 @@ int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap)
char *CDECL str_fmt(const char *str, ...) WARN_FORMAT(1, 2); char *CDECL str_fmt(const char *str, ...) WARN_FORMAT(1, 2);
void str_validate(char *str, const char *last, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK) NOACCESS(2); void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK) NOACCESS(2);
[[nodiscard]] std::string str_validate(const std::string &str, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK); [[nodiscard]] std::string StrMakeValid(const std::string &str, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK);
void ValidateString(const char *str); void StrMakeValidInPlace(const char *str, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK);
void str_fix_scc_encoded(char *str, const char *last) NOACCESS(2); void str_fix_scc_encoded(char *str, const char *last) NOACCESS(2);
void str_strip_colours(char *str); void str_strip_colours(char *str);

View File

@ -375,7 +375,7 @@ static void Xunzip(byte **bufp, size_t *sizep)
this->text = ReallocT(this->text, filesize + 1); this->text = ReallocT(this->text, filesize + 1);
this->text[filesize] = '\0'; this->text[filesize] = '\0';
/* Replace tabs and line feeds with a space since str_validate removes those. */ /* Replace tabs and line feeds with a space since StrMakeValidInPlace removes those. */
for (char *p = this->text; *p != '\0'; p++) { for (char *p = this->text; *p != '\0'; p++) {
if (*p == '\t' || *p == '\r') *p = ' '; if (*p == '\t' || *p == '\r') *p = ' ';
} }
@ -384,7 +384,7 @@ static void Xunzip(byte **bufp, size_t *sizep)
char *p = this->text + (strncmp(u8"\ufeff", this->text, 3) == 0 ? 3 : 0); char *p = this->text + (strncmp(u8"\ufeff", this->text, 3) == 0 ? 3 : 0);
/* Make sure the string is a valid UTF-8 sequence. */ /* Make sure the string is a valid UTF-8 sequence. */
str_validate(p, this->text + filesize, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE); StrMakeValidInPlace(p, this->text + filesize, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE);
/* Split the string on newlines. */ /* Split the string on newlines. */
int row = 0; int row = 0;

View File

@ -229,7 +229,7 @@ static void DedicatedHandleKeyInput()
break; break;
} }
} }
str_validate(input_line, lastof(input_line)); StrMakeValidInPlace(input_line, lastof(input_line));
IConsoleCmdExec(input_line); // execute command IConsoleCmdExec(input_line); // execute command
} }