Utils: Add more contains functions

We have very often the following pattern.

bool isKeyword(const QString &token)
{
    static const QStringList keywords = {"if", "then", "else", ...};

    return keywords.contains(token);
}

Instead we could remove the the allocation and give the compiler
the opportunity to transform the code. constexpr makes that prossible.

bool isKeyword(QStringView token)
{
static constexpr QStringView keywords[] = {u"if", u"then", u"else",
...};

    return Utils::contains(keywords, token);
}

Change-Id: Ic25aa676085bf4bfc6e9ff3194813ff019bd40af
Reviewed-by: Eike Ziller <eike.ziller@qt.io>
This commit is contained in:
Marco Bubke
2024-06-12 21:09:58 +02:00
parent 21d1ee2516
commit 8106d29cf4
2 changed files with 31 additions and 9 deletions

View File

@@ -455,6 +455,30 @@ bool contains(const C &container, R S::*member)
return anyOf(container, std::mem_fn(member)); return anyOf(container, std::mem_fn(member));
} }
template<typename T, std::size_t Size, typename V>
[[nodiscard]] bool contains(const T (&array)[Size], const V &value)
{
auto begin = std::begin(array);
auto end = std::end(array);
auto found = std::find(begin, end, value);
return found != end;
}
//////////////////
// containsInSorted
/////////////////
template<typename C, typename V>
[[nodiscard]] bool containsInSorted(const C &container, const V &value)
{
auto begin = std::begin(container);
auto end = std::end(container);
return std::binary_search(begin, end, value);
}
////////////////// //////////////////
// findOr // findOr
///////////////// /////////////////

View File

@@ -551,17 +551,15 @@ static QString replaceIllegalPropertyNameChars(const QString &str)
return ret; return ret;
} }
static bool idIsQmlKeyWord(const QString &id) static bool idIsQmlKeyWord(QStringView id)
{ {
static const QSet<QString> keywords = {"as", "break", "case", "catch", static constexpr std::u16string_view keywords[] = {
"continue", "debugger", "default", "delete", u"as", u"break", u"case", u"catch", u"continue", u"debugger", u"default",
"do", "else", "finally", "for", u"delete", u"do", u"else", u"finally", u"for", u"function", u"if",
"function", "if", "import", "in", u"import", u"in", u"instanceof", u"new", u"return", u"switch", u"this",
"instanceof", "new", "return", "switch", u"throw", u"try", u"typeof", u"var", u"void", u"while", u"with"};
"this", "throw", "try", "typeof",
"var", "void", "while", "with"};
return keywords.contains(id); return Utils::contains(keywords, std::u16string_view{id.utf16(), Utils::usize(id)});
} }
QString RewriterView::auxiliaryDataAsQML() const QString RewriterView::auxiliaryDataAsQML() const