Speed optimization for method QmuTokenParser::IsSingle().

--HG--
branch : develop
This commit is contained in:
Roman Telezhynskyi 2018-01-20 15:36:50 +02:00
parent d03cd7be06
commit e68510cc49
2 changed files with 7 additions and 38 deletions

View File

@ -96,44 +96,10 @@ QmuTokenParser::QmuTokenParser(const QString &formula, bool osSeparator,
*/
bool QmuTokenParser::IsSingle(const QString &formula)
{
if (formula.isEmpty())
{
return false;// if don't know say no
}
QScopedPointer<QmuTokenParser> cal(new QmuTokenParser());
// Parser doesn't know any variable on this stage. So, we just use variable factory that for each unknown
// variable set value to 0.
cal->SetVarFactory(AddVariable, cal.data());
cal->SetSepForEval();//Reset separators options
try
{
cal->SetExpr(formula);
cal->Eval();// We don't need save result, only parse formula
}
catch (const qmu::QmuParserError &e)
{
Q_UNUSED(e)
return false;// something wrong with formula, say no
}
QMap<int, QString> tokens = cal->GetTokens();// Tokens (variables, measurements)
const QMap<int, QString> numbers = cal->GetNumbers();// All numbers in expression
delete cal.take();
// Remove "-" from tokens list if exist. If don't do that unary minus operation will broken.
RemoveAll(tokens, QStringLiteral("-"));
if (tokens.isEmpty() && numbers.size() == 1)
{
return true;
}
else
{
return false;
}
QLocale c(QLocale::C);
bool ok = false;
c.toDouble(formula, &ok);
return ok;
}
}// namespace qmu

View File

@ -45,8 +45,10 @@ void TST_QmuTokenParser::IsSingle_data()
QTest::addColumn<QString>("formula");
QTest::addColumn<bool>("result");
QTest::newRow("Empty string") << "" << false;
QTest::newRow("Single value") << "15.5" << true;
QTest::newRow("Two digits") << "2+2" << false;
QTest::newRow("Two digits") << "2-2" << false;
QTest::newRow("Negative single value") << "-2" << true;
QTest::newRow("Digit and variable") << "2+a" << false;
QTest::newRow("One variable twice") << "a+a" << false;
@ -54,6 +56,7 @@ void TST_QmuTokenParser::IsSingle_data()
QTest::newRow("Empty string") << "" << false;
QTest::newRow("Several spaces") << " " << false;
QTest::newRow("Invalid formula") << "2*)))" << false;
QTest::newRow("Invalid formula") << "2*" << false;
QTest::newRow("Incorrect thousand separator 15 500") << "15 500" << false;
QTest::newRow("Correct C locale 15500") << "15500" << true;
QTest::newRow("Correct C locale 15,500") << "15,500" << true;