Strutils: add printf format validation

Moved from NewGUI code in FG, better it lives here for re-use.
This commit is contained in:
James Turner 2020-11-10 11:43:39 +00:00
parent f72e093714
commit ca857fcb25
2 changed files with 63 additions and 0 deletions

View File

@ -1587,6 +1587,56 @@ std::string formatGeodAsString(const SGGeod& geod, LatLonFormat format,
+ formatLatLonValueAsString(geod.getLongitudeDeg(), format, ew, degreeSymbol); + formatLatLonValueAsString(geod.getLongitudeDeg(), format, ew, degreeSymbol);
} }
PrintfFormatType validatePrintfFormat(const char* f)
{
bool l = false;
for (; *f; f++) {
if (*f == '%') {
if (f[1] == '%')
f++;
else
break;
}
}
if (*f++ != '%')
return PrintfFormatType::Invalid;
PrintfFormatType type = PrintfFormatType::Invalid;
while (*f == ' ' || *f == '+' || *f == '-' || *f == '#' || *f == '0')
f++;
while (*f && isdigit(*f))
f++;
if (*f == '.') {
f++;
while (*f && isdigit(*f))
f++;
}
if (*f == 'l')
l = true, f++;
if (*f == 'd') {
type = l ? PrintfFormatType::Long : PrintfFormatType::Int;
} else if (*f == 'f')
type = l ? PrintfFormatType::Double : PrintfFormatType::Float;
else if (*f == 's') {
if (l)
return PrintfFormatType::Invalid;
type = PrintfFormatType::CharPointer;
} else
return PrintfFormatType::Invalid;
for (++f; *f; f++) {
if (*f == '%') {
if (f[1] == '%')
f++;
else
return PrintfFormatType::Invalid;
}
}
return type;
}
} // end namespace strutils } // end namespace strutils
} // end namespace simgear } // end namespace simgear

View File

@ -448,6 +448,19 @@ namespace simgear {
std::string formatGeodAsString(const SGGeod& geod, std::string formatGeodAsString(const SGGeod& geod,
LatLonFormat format = LatLonFormat::DECIMAL_DEGREES, LatLonFormat format = LatLonFormat::DECIMAL_DEGREES,
DegreeSymbol degreeSymbol = DegreeSymbol::ASTERISK); DegreeSymbol degreeSymbol = DegreeSymbol::ASTERISK);
enum class PrintfFormatType {
Invalid,
Int,
Long,
Float,
Double,
CharPointer
};
PrintfFormatType validatePrintfFormat(const char* f);
} // end namespace strutils } // end namespace strutils
} // end namespace simgear } // end namespace simgear