Changeset - r28395:5c619adf84b5
[Not reviewed]
master
0 2 0
Peter Nelson - 11 months ago 2024-01-04 20:50:58
peter1138@openttd.org
Change: Don't handle 'missing' string parameters as 0. (#11673)

If not enough parameters are supplied for a string, then a value of 0 was used, which could result in incorrect information being displayed.

Instead, throw an exception and include an error in the string.
2 files changed with 9 insertions and 7 deletions:
0 comments (0 inline, 0 general)
src/strings.cpp
Show inline comments
 
@@ -81,15 +81,13 @@ StringParameter *StringParameters::GetNe
 
{
 
	assert(this->next_type == 0 || (SCC_CONTROL_START <= this->next_type && this->next_type <= SCC_CONTROL_END));
 
	if (this->offset >= this->parameters.size()) {
 
		Debug(misc, 0, "Trying to read invalid string parameter");
 
		return nullptr;
 
		throw std::out_of_range("Trying to read invalid string parameter");
 
	}
 

	
 
	auto &param = this->parameters[this->offset++];
 
	if (param.type != 0 && param.type != this->next_type) {
 
		Debug(misc, 0, "Trying to read string parameter with wrong type");
 
		this->next_type = 0;
 
		return nullptr;
 
		throw std::out_of_range("Trying to read string parameter with wrong type");
 
	}
 
	param.type = this->next_type;
 
	this->next_type = 0;
 
@@ -903,6 +901,7 @@ static void FormatString(StringBuilder &
 
	str_stack.push(str_arg);
 

	
 
	for (;;) {
 
		try {
 
		while (!str_stack.empty() && (b = Utf8Consume(&str_stack.top())) == '\0') {
 
			str_stack.pop();
 
		}
 
@@ -1105,7 +1104,7 @@ static void FormatString(StringBuilder &
 

	
 
			case SCC_RAW_STRING_POINTER: { // {RAW_STRING}
 
				const char *raw_string = args.GetNextParameterString();
 
				/* raw_string can be(come) nullptr when the parameter is out of range and 0 is returned instead. */
 
					/* raw_string can be nullptr. */
 
				if (raw_string == nullptr) {
 
					builder += "(invalid RAW_STRING parameter)";
 
					break;
 
@@ -1631,6 +1630,10 @@ static void FormatString(StringBuilder &
 
				builder.Utf8Encode(b);
 
				break;
 
		}
 
		} catch (std::out_of_range &e) {
 
			Debug(misc, 0, "FormatString: {}", e.what());
 
			builder += "(invalid parameter)";
 
		}
 
	}
 
}
 

	
src/strings_internal.h
Show inline comments
 
@@ -95,7 +95,7 @@ public:
 
	T GetNextParameter()
 
	{
 
		auto ptr = GetNextParameterPointer();
 
		return static_cast<T>(ptr == nullptr ? 0 : ptr->data);
 
		return static_cast<T>(ptr->data);
 
	}
 

	
 
	/**
 
@@ -107,7 +107,6 @@ public:
 
	const char *GetNextParameterString()
 
	{
 
		auto ptr = GetNextParameterPointer();
 
		if (ptr == nullptr) return nullptr;
 
		return ptr->string != nullptr ? ptr->string->c_str() : ptr->string_view;
 
	}
 

	
0 comments (0 inline, 0 general)