Utils: Convert to SmallStringView for comparison

Change-Id: I38d9716225b81091e8e75b26c9c2258a2aefa987
Reviewed-by: Tim Jenssen <tim.jenssen@qt.io>
This commit is contained in:
Marco Bubke
2017-08-29 12:54:10 +02:00
parent 7c0331ab93
commit 8640ef1927
26 changed files with 187 additions and 195 deletions

View File

@@ -34,9 +34,9 @@ namespace Sqlite {
class SQLITE_EXPORT SqliteException class SQLITE_EXPORT SqliteException
{ {
public: public:
SqliteException(Utils::SmallString &&whatErrorHasHappen, SqliteException(const char *whatErrorHasHappen,
Utils::SmallString &&sqliteErrorMessage = Utils::SmallString()) Utils::SmallString &&sqliteErrorMessage = Utils::SmallString())
: m_whatErrorHasHappen(std::move(whatErrorHasHappen)), : m_whatErrorHasHappen(whatErrorHasHappen),
m_sqliteErrorMessage(std::move(sqliteErrorMessage)) m_sqliteErrorMessage(std::move(sqliteErrorMessage))
{ {
} }
@@ -44,7 +44,7 @@ public:
void printWarning() const; void printWarning() const;
private: private:
Utils::SmallString m_whatErrorHasHappen; const char *m_whatErrorHasHappen;
Utils::SmallString m_sqliteErrorMessage; Utils::SmallString m_sqliteErrorMessage;
}; };

View File

@@ -242,11 +242,13 @@ public:
return SmallStringView(data(), size()); return SmallStringView(data(), size());
} }
explicit
operator QString() const operator QString() const
{ {
return toQString(); return toQString();
} }
explicit
operator std::string() const operator std::string() const
{ {
return std::string(data(), size()); return std::string(data(), size());
@@ -589,100 +591,6 @@ public:
return *(data() + index); return *(data() + index);
} }
template<size_type ArraySize>
friend bool operator==(const BasicSmallString& first, const char(&second)[ArraySize]) noexcept
{
return first == SmallStringView(second);
}
template<size_type ArraySize>
friend bool operator==(const char(&first)[ArraySize], const BasicSmallString& second) noexcept
{
return second == first;
}
template<typename Type,
typename = std::enable_if_t<std::is_pointer<Type>::value>
>
friend bool operator==(const BasicSmallString& first, Type second) noexcept
{
return first == SmallStringView(second);
}
template<typename Type,
typename = std::enable_if_t<std::is_pointer<Type>::value>
>
friend bool operator==(Type first, const BasicSmallString& second) noexcept
{
return second == first;
}
friend bool operator==(const BasicSmallString& first, const SmallStringView& second) noexcept
{
return first.size() == second.size()
&& std::memcmp(first.data(), second.data(), first.size()) == 0;
}
friend bool operator==(const SmallStringView& first, const BasicSmallString& second) noexcept
{
return second == first;
}
friend bool operator!=(const BasicSmallString& first, const SmallStringView& second) noexcept
{
return !(first == second);
}
friend bool operator!=(const SmallStringView& first, const BasicSmallString& second) noexcept
{
return second == first;
}
friend bool operator!=(const BasicSmallString& first, const BasicSmallString& second) noexcept
{
return !(first == second);
}
template<size_type ArraySize>
friend bool operator!=(const BasicSmallString& first, const char(&second)[ArraySize]) noexcept
{
return !(first == second);
}
template<size_type ArraySize>
friend bool operator!=(const char(&first)[ArraySize], const BasicSmallString& second) noexcept
{
return second != first;
}
template<typename Type,
typename = std::enable_if_t<std::is_pointer<Type>::value>
>
friend bool operator!=(const BasicSmallString& first, Type second) noexcept
{
return !(first == second);
}
template<typename Type,
typename = std::enable_if_t<std::is_pointer<Type>::value>
>
friend bool operator!=(Type first, const BasicSmallString& second) noexcept
{
return second != first;
}
friend bool operator<(const BasicSmallString& first, SmallStringView second) noexcept
{
return first.size() < second.size()
|| (first.size() == second.size() && std::memcmp(first.data(), second.data(), first.size()) < 0);
}
friend bool operator<(SmallStringView first, const BasicSmallString& second) noexcept
{
return first.size() < second.size()
|| (first.size() == second.size() && std::memcmp(first.data(), second.data(), first.size()) < 0);
}
friend BasicSmallString operator+(const BasicSmallString &first, const BasicSmallString &second) friend BasicSmallString operator+(const BasicSmallString &first, const BasicSmallString &second)
{ {
BasicSmallString text; BasicSmallString text;
@@ -994,29 +902,6 @@ template<template<uint> class String, uint Size>
using isSameString = std::is_same<std::remove_reference_t<std::remove_cv_t<String<Size>>>, using isSameString = std::is_same<std::remove_reference_t<std::remove_cv_t<String<Size>>>,
BasicSmallString<Size>>; BasicSmallString<Size>>;
template<template<uint> class String,
uint SizeOne,
uint SizeTwo,
typename = std::enable_if_t<isSameString<String, SizeOne>::value
|| isSameString<String, SizeTwo>::value>>
bool operator==(const String<SizeOne> &first, const String<SizeTwo> &second) noexcept
{
return first.size() == second.size()
&& std::memcmp(first.data(), second.data(), first.size()) == 0;
}
template<template<uint> class String,
uint SizeOne,
uint SizeTwo,
typename = std::enable_if_t<isSameString<String, SizeOne>::value
|| isSameString<String, SizeTwo>::value>>
bool operator<(const String<SizeOne> &first, const String<SizeTwo> &second) noexcept
{
return first.size() < second.size()
|| (first.size() == second.size() && std::memcmp(first.data(), second.data(), first.size()) < 0);
}
template<typename Key, template<typename Key,
typename Value, typename Value,
typename Hash = std::hash<Key>, typename Hash = std::hash<Key>,

View File

@@ -29,9 +29,15 @@ namespace Utils {
using uint = unsigned int; using uint = unsigned int;
class SmallStringView;
template <uint Size> template <uint Size>
class BasicSmallString; class BasicSmallString;
using SmallString = BasicSmallString<31>; using SmallString = BasicSmallString<31>;
using PathString = BasicSmallString<190>; using PathString = BasicSmallString<190>;
inline
int compare(SmallStringView first, SmallStringView second) noexcept;
inline
int reverseCompare(SmallStringView first, SmallStringView second) noexcept;
} // namespace Utils } // namespace Utils

View File

@@ -41,6 +41,7 @@ struct SmallStringIterator : public std::iterator<Category, Type, DistanceType,
{ {
SmallStringIterator() noexcept = default; SmallStringIterator() noexcept = default;
constexpr
SmallStringIterator(Pointer ptr) noexcept : pointer_(ptr) SmallStringIterator(Pointer ptr) noexcept : pointer_(ptr)
{ {
} }

View File

@@ -56,12 +56,12 @@ public:
{ {
} }
const char *data() const const char *data() const noexcept
{ {
return Q_LIKELY(isShortString()) ? m_data.shortString.string : m_data.allocated.data.pointer; return Q_LIKELY(isShortString()) ? m_data.shortString.string : m_data.allocated.data.pointer;
} }
size_type size() const size_type size() const noexcept
{ {
return Q_LIKELY(isShortString()) ? m_data.shortString.shortStringSize : m_data.allocated.data.size; return Q_LIKELY(isShortString()) ? m_data.shortString.shortStringSize : m_data.allocated.data.size;
} }

View File

@@ -138,7 +138,8 @@ public:
QStringList qStringList; QStringList qStringList;
qStringList.reserve(int(Base::size())); qStringList.reserve(int(Base::size()));
std::copy(Base::begin(), Base::end(), std::back_inserter(qStringList)); for (const auto &entry : *this)
qStringList.push_back(QString(entry));
return qStringList; return qStringList;
} }

View File

@@ -67,6 +67,12 @@ public:
{ {
} }
SmallStringView(const std::string &string) noexcept
: m_pointer(string.data()),
m_size(string.size())
{
}
static static
SmallStringView fromUtf8(const char *const characterPointer) SmallStringView fromUtf8(const char *const characterPointer)
{ {
@@ -74,19 +80,19 @@ public:
} }
constexpr constexpr
const char *data() const const char *data() const noexcept
{ {
return m_pointer; return m_pointer;
} }
constexpr constexpr
size_type size() const size_type size() const noexcept
{ {
return m_size; return m_size;
} }
constexpr constexpr
size_type isEmpty() const size_type isEmpty() const noexcept
{ {
return m_size == 0; return m_size == 0;
} }
@@ -140,19 +146,19 @@ private:
}; };
inline inline
bool operator==(const SmallStringView& first, const SmallStringView& second) noexcept bool operator==(SmallStringView first, SmallStringView second) noexcept
{ {
return first.size() == second.size() && std::memcmp(first.data(), second.data(), first.size()) == 0; return first.size() == second.size() && std::memcmp(first.data(), second.data(), first.size()) == 0;
} }
inline inline
bool operator!=(const SmallStringView& first, const SmallStringView& second) noexcept bool operator!=(SmallStringView first, SmallStringView second) noexcept
{ {
return !(first == second); return !(first == second);
} }
inline inline
int compare(const SmallStringView& first, const SmallStringView& second) noexcept int compare(SmallStringView first, SmallStringView second) noexcept
{ {
int sizeDifference = int(first.size() - second.size()); int sizeDifference = int(first.size() - second.size());
@@ -162,6 +168,18 @@ int compare(const SmallStringView& first, const SmallStringView& second) noexcep
return sizeDifference; return sizeDifference;
} }
inline
bool operator<(SmallStringView first, SmallStringView second) noexcept
{
return compare(first, second) < 0;
}
inline
bool operator>(SmallStringView first, SmallStringView second) noexcept
{
return second < first;
}
namespace Internal { namespace Internal {
inline inline
int reverse_memcmp(const char *first, const char *second, size_t n) int reverse_memcmp(const char *first, const char *second, size_t n)
@@ -187,7 +205,7 @@ int reverse_memcmp(const char *first, const char *second, size_t n)
} }
inline inline
int reverseCompare(const SmallStringView& first, const SmallStringView& second) noexcept int reverseCompare(SmallStringView first, SmallStringView second) noexcept
{ {
int sizeDifference = int(first.size() - second.size()); int sizeDifference = int(first.size() - second.size());

View File

@@ -43,7 +43,7 @@ void PchManagerClient::alive()
void PchManagerClient::precompiledHeadersUpdated(ClangBackEnd::PrecompiledHeadersUpdatedMessage &&message) void PchManagerClient::precompiledHeadersUpdated(ClangBackEnd::PrecompiledHeadersUpdatedMessage &&message)
{ {
for (const ClangBackEnd::ProjectPartPch &projectPartPch : message.projectPartPchs()) for (const ClangBackEnd::ProjectPartPch &projectPartPch : message.projectPartPchs())
precompiledHeaderUpdated(projectPartPch.id(), projectPartPch.path()); precompiledHeaderUpdated(QString(projectPartPch.id()), QString(projectPartPch.path()));
} }
void PchManagerClient::precompiledHeaderRemoved(const QString &projectPartId) void PchManagerClient::precompiledHeaderRemoved(const QString &projectPartId)

View File

@@ -25,7 +25,7 @@
#pragma once #pragma once
#include <clangpchmanager_global.h> #include "clangpchmanager_global.h"
#include <filecontainerv2.h> #include <filecontainerv2.h>

View File

@@ -52,9 +52,9 @@ void ClangQueryHoverHandler::identifyMatch(TextEditor::TextEditorWidget *editorW
Contexts contexts = m_highligher->contextsForLineAndColumn(uint(line), uint(column)); Contexts contexts = m_highligher->contextsForLineAndColumn(uint(line), uint(column));
if (!messages.empty()) if (!messages.empty())
setToolTip(QString("%1: %2").arg(messages[0].errorTypeText()).arg(messages[0].arguments().join(", "))); setToolTip(QString("%1: %2").arg(QString(messages[0].errorTypeText())).arg(QString(messages[0].arguments().join(", "))));
else if (!contexts.empty()) else if (!contexts.empty())
setToolTip(QString("%1: %2").arg(contexts[0].contextTypeText()).arg(contexts[0].arguments().join(", "))); setToolTip(QString("%1: %2").arg(QString(contexts[0].contextTypeText())).arg(QString(contexts[0].arguments().join(", "))));
} }
} // namespace ClangRefactoring } // namespace ClangRefactoring

View File

@@ -154,7 +154,7 @@ void RefactoringClient::addSearchResult(const ClangBackEnd::SourceRangeWithTextC
std::unordered_map<uint, QString> &filePaths) std::unordered_map<uint, QString> &filePaths)
{ {
m_searchHandle->addResult(filePaths[sourceRangeWithText.fileHash()], m_searchHandle->addResult(filePaths[sourceRangeWithText.fileHash()],
sourceRangeWithText.text(), QString(sourceRangeWithText.text()),
{{int(sourceRangeWithText.start().line()), {{int(sourceRangeWithText.start().line()),
int(sourceRangeWithText.start().column() - 1), int(sourceRangeWithText.start().column() - 1),
int(sourceRangeWithText.start().offset())}, int(sourceRangeWithText.start().offset())},

View File

@@ -66,24 +66,24 @@ template <typename Source,
typename Target> typename Target>
void append(Target &target, const Source &source) void append(Target &target, const Source &source)
{ {
using ValueType = typename Target::value_type;
Source clonedSource = source.clone(); Source clonedSource = source.clone();
target.reserve(target.size() + source.size()); target.reserve(target.size() + source.size());
std::move(clonedSource.begin(), for(auto &&entry : clonedSource)
clonedSource.end(), target.push_back(ValueType(std::move(entry)));
std::back_inserter(target));
} }
template <typename Source, template <typename Source,
typename Target> typename Target>
void append(Target &target, Source &source) void append(Target &target, Source &source)
{ {
using ValueType = typename Target::value_type;
target.reserve(target.size() + source.size()); target.reserve(target.size() + source.size());
std::move(source.begin(), for(auto &&entry : source)
source.end(), target.push_back(ValueType(entry));
std::back_inserter(target));
} }
template <typename GetterFunction> template <typename GetterFunction>
@@ -469,14 +469,14 @@ std::vector<uint> PchCreator::generateProjectPartPchIncludes(
auto jointFile = generateFileWithContent(jointedFilePath, jointedFileContent); auto jointFile = generateFileWithContent(jointedFilePath, jointedFileContent);
Utils::SmallStringVector arguments = generateProjectPartCommandLine(projectPart); Utils::SmallStringVector arguments = generateProjectPartCommandLine(projectPart);
arguments.push_back(jointedFilePath); arguments.push_back(jointedFilePath);
FilePath filePath(jointedFilePath.clone()); FilePath filePath{Utils::PathString(jointedFilePath)};
IncludeCollector collector(m_filePathCache); IncludeCollector collector(m_filePathCache);
collector.setExcludedIncludes(generateProjectPartHeaderAndSourcePaths(projectPart)); collector.setExcludedIncludes(generateProjectPartHeaderAndSourcePaths(projectPart));
collector.addFile(filePath.directory(), collector.addFile(std::string(filePath.directory()),
filePath.name(), std::string(filePath.name()),
{}, {},
arguments); arguments);
@@ -581,11 +581,11 @@ std::unique_ptr<QFile> PchCreator::generateFileWithContent(
const Utils::SmallString &filePath, const Utils::SmallString &filePath,
const Utils::SmallString &content) const Utils::SmallString &content)
{ {
std::unique_ptr<QFile> precompiledIncludeFile(new QFile(filePath)); std::unique_ptr<QFile> precompiledIncludeFile(new QFile(QString(filePath)));
precompiledIncludeFile->open(QIODevice::WriteOnly); precompiledIncludeFile->open(QIODevice::WriteOnly);
precompiledIncludeFile->write(content.data(), content.size()); precompiledIncludeFile->write(content.data(), qint64(content.size()));
precompiledIncludeFile->close(); precompiledIncludeFile->close();
return precompiledIncludeFile; return precompiledIncludeFile;

View File

@@ -70,8 +70,8 @@ unittest_public:
Process *processPointer = process.get(); Process *processPointer = process.get();
process->setProcessChannelMode(QProcess::ForwardedChannels); process->setProcessChannelMode(QProcess::ForwardedChannels);
process->setArguments(compilerArguments); process->setArguments(QStringList(compilerArguments));
process->setProgram(m_environment.clangCompilerPath()); process->setProgram(QString(m_environment.clangCompilerPath()));
connectProcess(processPointer, std::move(projectPartPch)); connectProcess(processPointer, std::move(projectPartPch));

View File

@@ -50,10 +50,10 @@ ClangQueryGatherer::createSourceRangesForSource(
{ {
ClangQuery clangQuery(*filePathCache, std::move(query)); ClangQuery clangQuery(*filePathCache, std::move(query));
clangQuery.addFile(source.filePath().directory(), clangQuery.addFile(std::string(source.filePath().directory()),
source.filePath().name(), std::string(source.filePath().name()),
source.takeUnsavedFileContent(), std::string(source.takeUnsavedFileContent()),
source.takeCommandLineArguments()); std::vector<std::string>(source.takeCommandLineArguments()));
clangQuery.addUnsavedFiles(unsaved); clangQuery.addUnsavedFiles(unsaved);

View File

@@ -68,7 +68,7 @@ void ClangTool::addFiles(const Container &filePaths,
auto fileNameBegin = found.base(); auto fileNameBegin = found.base();
std::vector<std::string> commandLine(arguments.begin(), arguments.end()); std::vector<std::string> commandLine(arguments.begin(), arguments.end());
commandLine.push_back(filePath); commandLine.push_back(std::string(filePath));
addFile({filePath.begin(), std::prev(fileNameBegin)}, addFile({filePath.begin(), std::prev(fileNameBegin)},
{fileNameBegin, filePath.end()}, {fileNameBegin, filePath.end()},

View File

@@ -66,7 +66,7 @@ public:
std::string takeSymbolName() std::string takeSymbolName()
{ {
return std::move(symbolName); return std::string(symbolName);
} }
std::vector<USRName> takeUnifiedSymbolResolutions() std::vector<USRName> takeUnifiedSymbolResolutions()

View File

@@ -56,10 +56,10 @@ void RefactoringServer::requestSourceLocationsForRenamingMessage(RequestSourceLo
{ {
SymbolFinder symbolFinder(message.line(), message.column()); SymbolFinder symbolFinder(message.line(), message.column());
symbolFinder.addFile(message.filePath().directory(), symbolFinder.addFile(std::string(message.filePath().directory()),
message.filePath().name(), std::string(message.filePath().name()),
message.unsavedContent(), std::string(message.unsavedContent()),
message.commandLine()); std::vector<std::string>(message.commandLine()));
symbolFinder.findSymbol(); symbolFinder.findSymbol();
@@ -73,10 +73,10 @@ void RefactoringServer::requestSourceRangesAndDiagnosticsForQueryMessage(
{ {
ClangQuery clangQuery(m_filePathCache, message.takeQuery()); ClangQuery clangQuery(m_filePathCache, message.takeQuery());
clangQuery.addFile(message.source().filePath().directory(), clangQuery.addFile(std::string(message.source().filePath().directory()),
message.source().filePath().name(), std::string(message.source().filePath().name()),
message.source().unsavedFileContent(), std::string(message.source().unsavedFileContent()),
message.source().commandLineArguments()); std::vector<std::string>(message.source().commandLineArguments()));
clangQuery.findLocations(); clangQuery.findLocations();

View File

@@ -68,7 +68,7 @@ TEST_F(ClangPathWatcher, ConvertWatcherEntriesToQStringList)
{ {
auto convertedList = watcher.convertWatcherEntriesToQStringList({watcherEntry1, watcherEntry3}); auto convertedList = watcher.convertWatcherEntriesToQStringList({watcherEntry1, watcherEntry3});
ASSERT_THAT(convertedList, ElementsAre(path1, path2)); ASSERT_THAT(convertedList, ElementsAre(QString(path1), QString(path2)));
} }
TEST_F(ClangPathWatcher, UniquePaths) TEST_F(ClangPathWatcher, UniquePaths)
@@ -89,7 +89,7 @@ TEST_F(ClangPathWatcher, NotWatchedEntries)
TEST_F(ClangPathWatcher, AddIdPaths) TEST_F(ClangPathWatcher, AddIdPaths)
{ {
EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{path1, path2})); EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{QString(path1), QString(path2)}));
watcher.updateIdPaths({{id1, {paths[0], paths[1]}}, {id2, {paths[0], paths[1]}}}); watcher.updateIdPaths({{id1, {paths[0], paths[1]}}, {id2, {paths[0], paths[1]}}});
} }
@@ -98,7 +98,7 @@ TEST_F(ClangPathWatcher, UpdateIdPathsCallsAddPathInFileWatcher)
{ {
watcher.updateIdPaths({{id1, {paths[0]}}, {id2, {paths[0]}}}); watcher.updateIdPaths({{id1, {paths[0]}}, {id2, {paths[0]}}});
EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{path2})); EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{QString(path2)}));
watcher.updateIdPaths({{id1, {paths[0], paths[1]}}, {id2, {paths[0], paths[1]}}}); watcher.updateIdPaths({{id1, {paths[0], paths[1]}}, {id2, {paths[0], paths[1]}}});
} }
@@ -107,7 +107,7 @@ TEST_F(ClangPathWatcher, UpdateIdPathsAndRemoveUnusedPathsCallsRemovePathInFileW
{ {
watcher.updateIdPaths({{id1, {paths[0], paths[1]}}, {id2, {paths[0], paths[1]}}, {id3, {paths[0]}}}); watcher.updateIdPaths({{id1, {paths[0], paths[1]}}, {id2, {paths[0], paths[1]}}, {id3, {paths[0]}}});
EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{path2})); EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{QString(path2)}));
watcher.updateIdPaths({{id1, {paths[0]}}, {id2, {paths[0]}}}); watcher.updateIdPaths({{id1, {paths[0]}}, {id2, {paths[0]}}});
} }
@@ -116,7 +116,7 @@ TEST_F(ClangPathWatcher, UpdateIdPathsAndRemoveUnusedPathsDoNotCallsRemovePathIn
{ {
watcher.updateIdPaths({{id1, {paths[0], paths[1]}}, {id2, {paths[0], paths[1]}}, {id3, {paths[0]}}}); watcher.updateIdPaths({{id1, {paths[0], paths[1]}}, {id2, {paths[0], paths[1]}}, {id3, {paths[0]}}});
EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{path2})) EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{QString(path2)}))
.Times(0); .Times(0);
watcher.updateIdPaths({{id1, {paths[1]}}, {id2, {paths[0]}}}); watcher.updateIdPaths({{id1, {paths[1]}}, {id2, {paths[0]}}});
@@ -189,14 +189,14 @@ TEST_F(ClangPathWatcher, AddEmptyEntries)
TEST_F(ClangPathWatcher, AddEntriesWithSameIdAndDifferentPaths) TEST_F(ClangPathWatcher, AddEntriesWithSameIdAndDifferentPaths)
{ {
EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{path1, path2})); EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{QString(path1), QString(path2)}));
watcher.addEntries({watcherEntry1, watcherEntry3}); watcher.addEntries({watcherEntry1, watcherEntry3});
} }
TEST_F(ClangPathWatcher, AddEntriesWithDifferentIdAndSamePaths) TEST_F(ClangPathWatcher, AddEntriesWithDifferentIdAndSamePaths)
{ {
EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{path1})); EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{QString(path1)}));
watcher.addEntries({watcherEntry1, watcherEntry2}); watcher.addEntries({watcherEntry1, watcherEntry2});
} }
@@ -205,7 +205,7 @@ TEST_F(ClangPathWatcher, DontAddNewEntriesWithSameIdAndSamePaths)
{ {
watcher.addEntries({watcherEntry1}); watcher.addEntries({watcherEntry1});
EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{path1})) EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{QString(path1)}))
.Times(0); .Times(0);
watcher.addEntries({watcherEntry1}); watcher.addEntries({watcherEntry1});
@@ -215,7 +215,7 @@ TEST_F(ClangPathWatcher, DontAddNewEntriesWithDifferentIdAndSamePaths)
{ {
watcher.addEntries({watcherEntry1}); watcher.addEntries({watcherEntry1});
EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{path1})) EXPECT_CALL(mockQFileSytemWatcher, addPaths(QStringList{QString(path1)}))
.Times(0); .Times(0);
watcher.addEntries({watcherEntry2}); watcher.addEntries({watcherEntry2});
@@ -252,7 +252,7 @@ TEST_F(ClangPathWatcher, RemovePathForOneId)
{ {
watcher.addEntries({watcherEntry1, watcherEntry2, watcherEntry3}); watcher.addEntries({watcherEntry1, watcherEntry2, watcherEntry3});
EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{path2})); EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{QString(path2)}));
watcher.removeIds({id1}); watcher.removeIds({id1});
} }
@@ -261,7 +261,7 @@ TEST_F(ClangPathWatcher, RemoveAllPathsForThreeId)
{ {
watcher.addEntries({watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4, watcherEntry5}); watcher.addEntries({watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4, watcherEntry5});
EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{path1, path2})); EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{QString(path1), QString(path2)}));
watcher.removeIds({id1, id2, id3}); watcher.removeIds({id1, id2, id3});
} }
@@ -270,7 +270,7 @@ TEST_F(ClangPathWatcher, RemoveOnePathForTwoId)
{ {
watcher.addEntries({watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4, watcherEntry5}); watcher.addEntries({watcherEntry1, watcherEntry2, watcherEntry3, watcherEntry4, watcherEntry5});
EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{path1})); EXPECT_CALL(mockQFileSytemWatcher, removePaths(QStringList{QString(path1)}));
watcher.removeIds({id1, id2}); watcher.removeIds({id1, id2});
} }

View File

@@ -170,7 +170,7 @@ TEST_F(ClangQueryProjectFindFilter, CallingRequestSourceRangesAndDiagnostics)
Property(&FileContainer::unsavedFileContent, exampleContent)), Property(&FileContainer::unsavedFileContent, exampleContent)),
Property(&Message::query, queryText)))); Property(&Message::query, queryText))));
findFilter.requestSourceRangesAndDiagnostics(queryText, exampleContent); findFilter.requestSourceRangesAndDiagnostics(QString(queryText), QString(exampleContent));
} }
std::vector<CppTools::ProjectPart::Ptr> createProjectParts() std::vector<CppTools::ProjectPart::Ptr> createProjectParts()

View File

@@ -39,3 +39,5 @@
#endif #endif
#include "google-using-declarations.h" #include "google-using-declarations.h"
#include "unittest-matchers.h"

View File

@@ -51,7 +51,6 @@ using testing::AtLeast;
using testing::ContainerEq; using testing::ContainerEq;
using testing::Contains; using testing::Contains;
using testing::ElementsAre; using testing::ElementsAre;
using testing::EndsWith;
using testing::Eq; using testing::Eq;
using testing::Field; using testing::Field;
using testing::HasSubstr; using testing::HasSubstr;
@@ -61,11 +60,12 @@ using testing::Not;
using testing::Property; using testing::Property;
using testing::SizeIs; using testing::SizeIs;
using testing::UnorderedElementsAre; using testing::UnorderedElementsAre;
using UnitTests::EndsWith;
class PchCreator: public ::testing::Test class PchCreator: public ::testing::Test
{ {
protected: protected:
uint id(const Utils::SmallString &path); uint id(const Utils::PathString &path);
protected: protected:
ClangBackEnd::StringCache<Utils::PathString> filePathCache; ClangBackEnd::StringCache<Utils::PathString> filePathCache;
@@ -148,7 +148,7 @@ TEST_F(PchCreatorVerySlowTest, CreateGlobalPchFileContent)
{ {
auto content = creator.generateGlobalPchHeaderFileContent(); auto content = creator.generateGlobalPchHeaderFileContent();
ASSERT_THAT(content, ASSERT_THAT(std::string(content),
AllOf(HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external3.h\"\n"), AllOf(HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external3.h\"\n"),
HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external1.h\"\n"), HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external1.h\"\n"),
HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external2.h\"\n"))); HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external2.h\"\n")));
@@ -228,7 +228,7 @@ TEST_F(PchCreatorSlowTest, CreateProjectPartPchFileContent)
auto content = creator.generatePchIncludeFileContent(includes); auto content = creator.generatePchIncludeFileContent(includes);
ASSERT_THAT(content, ASSERT_THAT(std::string(content),
AllOf(HasSubstr("#include \"" TESTDATA_DIR "/includecollector_header2.h\"\n"), AllOf(HasSubstr("#include \"" TESTDATA_DIR "/includecollector_header2.h\"\n"),
HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external1.h\"\n"), HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external1.h\"\n"),
HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external2.h\"\n"))); HasSubstr("#include \"" TESTDATA_DIR "/includecollector_external2.h\"\n")));
@@ -282,7 +282,7 @@ TEST_F(PchCreatorVerySlowTest, ProjectPartPchsExistsAfterCreation)
creator.generateProjectPartPch(projectPart1); creator.generateProjectPartPch(projectPart1);
ASSERT_TRUE(QFileInfo::exists(creator.generateProjectPathPchHeaderFilePath(projectPart1))); ASSERT_TRUE(QFileInfo::exists(QString(creator.generateProjectPathPchHeaderFilePath(projectPart1))));
} }
TEST_F(PchCreatorVerySlowTest, DISABLED_CreatePartPchs) TEST_F(PchCreatorVerySlowTest, DISABLED_CreatePartPchs)
@@ -340,7 +340,7 @@ TEST_F(PchCreator, CreateProjectPartHeaderAndSourcesContent)
"#include \"" TESTDATA_DIR "/includecollector_main3.cpp\"\n")); "#include \"" TESTDATA_DIR "/includecollector_main3.cpp\"\n"));
} }
uint PchCreator::id(const Utils::SmallString &path) uint PchCreator::id(const Utils::PathString &path)
{ {
return filePathCache.stringId(path); return filePathCache.stringId(path);
} }

View File

@@ -86,7 +86,8 @@ TEST_F(PchManagerClient, Remove)
EXPECT_CALL(mockPchManagerNotifier, precompiledHeaderRemoved(projectPartId.toQString())) EXPECT_CALL(mockPchManagerNotifier, precompiledHeaderRemoved(projectPartId.toQString()))
.Times(2); .Times(2);
projectUpdater.removeProjectParts({projectPartId.clone(), projectPartId.clone()}); projectUpdater.removeProjectParts({QString(projectPartId.clone()),
QString(projectPartId.clone())});
} }
} }

View File

@@ -65,10 +65,10 @@ protected:
Utils::SmallString projectPartId2{"project2"}; Utils::SmallString projectPartId2{"project2"};
Utils::PathStringVector headerPaths = {"/path/to/header1.h", "/path/to/header2.h"}; Utils::PathStringVector headerPaths = {"/path/to/header1.h", "/path/to/header2.h"};
Utils::PathStringVector sourcePaths = {"/path/to/source1.cpp", "/path/to/source2.cpp"}; Utils::PathStringVector sourcePaths = {"/path/to/source1.cpp", "/path/to/source2.cpp"};
CppTools::ProjectFile header1ProjectFile{headerPaths[0], CppTools::ProjectFile::CXXHeader}; CppTools::ProjectFile header1ProjectFile{QString(headerPaths[0]), CppTools::ProjectFile::CXXHeader};
CppTools::ProjectFile header2ProjectFile{headerPaths[1], CppTools::ProjectFile::CXXHeader}; CppTools::ProjectFile header2ProjectFile{QString(headerPaths[1]), CppTools::ProjectFile::CXXHeader};
CppTools::ProjectFile source1ProjectFile{sourcePaths[0], CppTools::ProjectFile::CXXSource}; CppTools::ProjectFile source1ProjectFile{QString(sourcePaths[0]), CppTools::ProjectFile::CXXSource};
CppTools::ProjectFile source2ProjectFile{sourcePaths[1], CppTools::ProjectFile::CXXSource}; CppTools::ProjectFile source2ProjectFile{QString(sourcePaths[1]), CppTools::ProjectFile::CXXSource};
CppTools::ProjectPart projectPart; CppTools::ProjectPart projectPart;
ProjectPartContainer expectedContainer; ProjectPartContainer expectedContainer;
FileContainer generatedFile{{"/path/to", "header1.h"}, "content", {}}; FileContainer generatedFile{{"/path/to", "header1.h"}, "content", {}};
@@ -92,7 +92,7 @@ TEST_F(ProjectUpdater, CallRemovePchProjectParts)
EXPECT_CALL(mockPchManagerServer, removePchProjectParts(message)); EXPECT_CALL(mockPchManagerServer, removePchProjectParts(message));
updater.removeProjectParts({projectPartId, projectPartId2}); updater.removeProjectParts({QString(projectPartId), QString(projectPartId2)});
} }
TEST_F(ProjectUpdater, CallPrecompiledHeaderRemoved) TEST_F(ProjectUpdater, CallPrecompiledHeaderRemoved)
@@ -102,7 +102,7 @@ TEST_F(ProjectUpdater, CallPrecompiledHeaderRemoved)
EXPECT_CALL(mockPchManagerNotifier, precompiledHeaderRemoved(projectPartId.toQString())); EXPECT_CALL(mockPchManagerNotifier, precompiledHeaderRemoved(projectPartId.toQString()));
EXPECT_CALL(mockPchManagerNotifier, precompiledHeaderRemoved(projectPartId2.toQString())); EXPECT_CALL(mockPchManagerNotifier, precompiledHeaderRemoved(projectPartId2.toQString()));
updater.removeProjectParts({projectPartId, projectPartId2}); updater.removeProjectParts({QString(projectPartId), QString(projectPartId2)});
} }
TEST_F(ProjectUpdater, ConvertProjectPartToProjectPartContainer) TEST_F(ProjectUpdater, ConvertProjectPartToProjectPartContainer)
@@ -134,7 +134,7 @@ void ProjectUpdater::SetUp()
projectPart.files.push_back(header2ProjectFile); projectPart.files.push_back(header2ProjectFile);
projectPart.files.push_back(source1ProjectFile); projectPart.files.push_back(source1ProjectFile);
projectPart.files.push_back(source2ProjectFile); projectPart.files.push_back(source2ProjectFile);
projectPart.displayName = projectPartId; projectPart.displayName = QString(projectPartId);
Utils::SmallStringVector arguments{ClangPchManager::ProjectUpdater::compilerArguments( Utils::SmallStringVector arguments{ClangPchManager::ProjectUpdater::compilerArguments(
&projectPart)}; &projectPart)};

View File

@@ -69,7 +69,7 @@ TEST_F(RefactoringCompilationDatabase, GetAllFilesContainsTranslationUnit)
{ {
auto filePaths = database.getAllFiles(); auto filePaths = database.getAllFiles();
ASSERT_THAT(filePaths, Contains(temporarySourceFilePath)); ASSERT_THAT(filePaths, Contains(std::string(temporarySourceFilePath)));
} }
TEST_F(RefactoringCompilationDatabase, CompileCommandForFilePath) TEST_F(RefactoringCompilationDatabase, CompileCommandForFilePath)
@@ -94,12 +94,12 @@ TEST_F(RefactoringCompilationDatabase, FilePaths)
{ {
auto filePaths = database.getAllFiles(); auto filePaths = database.getAllFiles();
ASSERT_THAT(filePaths, Contains(temporarySourceFilePath)); ASSERT_THAT(filePaths, Contains(std::string(temporarySourceFilePath)));
} }
void RefactoringCompilationDatabase::SetUp() void RefactoringCompilationDatabase::SetUp()
{ {
database.addFile(temporaryDirectoryPath, "data.cpp", {"cc", "data.cpp", "-DNO_DEBUG"}); database.addFile(std::string(temporaryDirectoryPath), "data.cpp", {"cc", "data.cpp", "-DNO_DEBUG"});
} }
} }

View File

@@ -86,7 +86,7 @@ TEST_F(SourceRangeExtractorSlowTest, FindStartOfLineInEmptyBuffer)
auto found = ::SourceRangeExtractor::findStartOfLineInBuffer(text, 0); auto found = ::SourceRangeExtractor::findStartOfLineInBuffer(text, 0);
ASSERT_THAT(found, StrEq("")); ASSERT_THAT(found, Eq(""));
} }
TEST_F(SourceRangeExtractorSlowTest, FindStartOfLineInBufferInFirstLine) TEST_F(SourceRangeExtractorSlowTest, FindStartOfLineInBufferInFirstLine)
@@ -95,7 +95,7 @@ TEST_F(SourceRangeExtractorSlowTest, FindStartOfLineInBufferInFirstLine)
auto found = ::SourceRangeExtractor::findStartOfLineInBuffer(text, 5); auto found = ::SourceRangeExtractor::findStartOfLineInBuffer(text, 5);
ASSERT_THAT(found, StrEq("first line")); ASSERT_THAT(found, Eq("first line"));
} }
TEST_F(SourceRangeExtractorSlowTest, FindStartOfNewLineInBufferInSecondLine) TEST_F(SourceRangeExtractorSlowTest, FindStartOfNewLineInBufferInSecondLine)
@@ -167,7 +167,7 @@ TEST_F(SourceRangeExtractorSlowTest, EpandText)
auto expandedText = ::SourceRangeExtractor::getExpandedText(text, 15, 25); auto expandedText = ::SourceRangeExtractor::getExpandedText(text, 15, 25);
ASSERT_THAT(expandedText, StrEq("second line\nthird line")); ASSERT_THAT(expandedText, Eq("second line\nthird line"));
} }
void SourceRangeExtractor::SetUp() void SourceRangeExtractor::SetUp()

View File

@@ -0,0 +1,78 @@
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#pragma once
#include <gmock/gmock-matchers.h>
#include <utils/smallstringio.h>
namespace UnitTests {
template <typename StringType>
class EndsWithMatcher
{
public:
explicit EndsWithMatcher(const StringType& suffix) : m_suffix(suffix) {}
template <typename CharType>
bool MatchAndExplain(CharType *s, testing::MatchResultListener *listener) const
{
return s != NULL && MatchAndExplain(StringType(s), listener);
}
template <typename MatcheeStringType>
bool MatchAndExplain(const MatcheeStringType& s,
testing::MatchResultListener* /* listener */) const
{
return s.endsWith(m_suffix);
}
void DescribeTo(::std::ostream* os) const
{
*os << "ends with " << m_suffix;
}
void DescribeNegationTo(::std::ostream* os) const
{
*os << "doesn't end with " << m_suffix;
}
EndsWithMatcher(EndsWithMatcher const &) = default;
EndsWithMatcher &operator=(EndsWithMatcher const &) = delete;
private:
const StringType m_suffix;
};
inline
testing::PolymorphicMatcher<EndsWithMatcher<Utils::SmallString> >
EndsWith(const Utils::SmallString &suffix)
{
return testing::MakePolymorphicMatcher(EndsWithMatcher<Utils::SmallString>(suffix));
}
}