Reduce complexity of regular expression initialization

This commit is contained in:
Rasmus Karlsson 2018-06-28 00:48:25 +02:00 committed by fourtf
parent 20c17c3377
commit 524be95e8b

View file

@ -1,30 +1,24 @@
#include "common/LinkParser.hpp" #include "common/LinkParser.hpp"
#include "debug/Log.hpp"
#include <QFile> #include <QFile>
#include <QRegularExpression> #include <QRegularExpression>
#include <QString> #include <QString>
#include <QTextStream> #include <QTextStream>
#include <mutex>
namespace chatterino { namespace chatterino {
namespace { LinkParser::LinkParser(const QString &unparsedString)
std::once_flag regexInitializedFlag;
QRegularExpression *linkRegex = nullptr;
void initializeRegularExpressions()
{ {
std::call_once(regexInitializedFlag, [] { static QRegularExpression linkRegex = [] {
QFile tldFile(":/tlds.txt"); QFile tldFile(":/tlds.txt");
tldFile.open(QFile::ReadOnly); tldFile.open(QFile::ReadOnly);
QTextStream t1(&tldFile); QTextStream t1(&tldFile);
t1.setCodec("UTF-8"); t1.setCodec("UTF-8");
QString tldData = t1.readAll();
tldData.replace("\n", "|"); // Read the TLDs in and replace the newlines with pipes
QString tldData = t1.readAll().replace("\n", "|");
const QString urlRegExp = const QString urlRegExp =
"^" "^"
// protocol identifier // protocol identifier
@ -57,21 +51,11 @@ void initializeRegularExpressions()
// resource path // resource path
"(?:[/?#]\\S*)?" "(?:[/?#]\\S*)?"
"$"; "$";
linkRegex = new QRegularExpression(urlRegExp, QRegularExpression::CaseInsensitiveOption);
Log("fully initialized"); return QRegularExpression(urlRegExp, QRegularExpression::CaseInsensitiveOption);
}); }();
Log("call_once returned"); this->match_ = linkRegex.match(unparsedString);
}
} // namespace
LinkParser::LinkParser(const QString &unparsedString)
{
initializeRegularExpressions();
this->match_ = linkRegex->match(unparsedString);
} }
} // namespace chatterino } // namespace chatterino