Replace Util::startsWith/endsWith w/ C++20 equivalent

Replace a few cases of Util::toString(...), too.

Signed-off-by: Aron Budea <aron.budea@collabora.com>
Change-Id: I53c5dbbdf2f60710e94add9dd137aa9becb7bd3e
pull/8356/head
Aron Budea 2024-02-22 14:42:57 +10:30 committed by Miklos Vajna
parent 8adfaedd45
commit 3b8f3d07f6
24 changed files with 50 additions and 82 deletions

View File

@ -421,7 +421,7 @@ bool UnitBase::filterSendWebSocketMessage(const char* data, const std::size_t le
const WSOpCode code, const bool flush, int& unitReturn)
{
const std::string message(data, len);
if (Util::startsWith(message, "unocommandresult:"))
if (message.starts_with("unocommandresult:"))
{
const std::size_t index = message.find_first_of('{');
if (index != std::string::npos)
@ -458,7 +458,7 @@ bool UnitBase::filterSendWebSocketMessage(const char* data, const std::size_t le
LOG_TST("Expected json unocommandresult. Ignoring: " << message);
}
}
else if (Util::startsWith(message, "status:"))
else if (message.starts_with("status:"))
{
if (onDocumentLoaded(message))
return false;
@ -473,12 +473,12 @@ bool UnitBase::filterSendWebSocketMessage(const char* data, const std::size_t le
if (onDocumentUnmodified(message))
return false;
}
else if (Util::startsWith(message, "statechanged:"))
else if (message.starts_with("statechanged:"))
{
if (onDocumentStateChanged(message))
return false;
}
else if (Util::startsWith(message, "error:"))
else if (message.starts_with("error:"))
{
if (onDocumentError(message))
return false;

View File

@ -613,30 +613,6 @@ namespace Util
return trimmed(std::string(s));
}
/// Return true iff s starts with t.
inline bool startsWith(const std::string& s, const std::string& t)
{
return s.length() >= t.length() && memcmp(s.c_str(), t.c_str(), t.length()) == 0;
}
/// Return true iff s starts with t.
inline bool startsWith(const std::string& s, const char* t)
{
if (t != nullptr && !s.empty())
{
const size_t len = std::strlen(t);
return s.length() >= len && memcmp(s.c_str(), t, len) == 0;
}
return false;
}
/// Return true iff s ends with t.
inline bool endsWith(const std::string& s, const std::string& t)
{
return equal(t.rbegin(), t.rend(), s.rbegin());
}
#ifdef IOS
inline void *memrchr(const void *s, int c, size_t n)

View File

@ -783,7 +783,7 @@ bool ChildSession::loadDocument(const StringVector& tokens)
if (!_jailRoot.empty())
{
url = Protocol + _jailRoot;
if (Util::startsWith(getJailedFilePath(), Protocol))
if (getJailedFilePath().starts_with(Protocol))
url += getJailedFilePath().substr(sizeof(Protocol) - 1);
else
url += getJailedFilePath();
@ -1413,7 +1413,7 @@ bool ChildSession::insertFile(const StringVector& tokens)
else if (type == "graphicurl")
{
URI::decode(name, url);
if (!Util::startsWith(Util::toLower(url), "http"))
if (!Util::toLower(url).starts_with("http"))
{
// Do not allow arbitrary schemes, especially "file://".
sendTextFrameAndLogError("error: cmd=insertfile kind=syntax");
@ -2891,7 +2891,7 @@ void ChildSession::loKitCallback(const int type, const std::string& payload)
break;
case LOK_CALLBACK_STATE_CHANGED:
sendTextFrame("statechanged: " + payload);
if (Util::startsWith(payload, ".uno:SlideMasterPage"))
if (payload.starts_with(".uno:SlideMasterPage"))
{
std::string status = LOKitHelper::documentStatus(getLOKitDocument()->get());
sendTextFrame("status: " + status);

View File

@ -557,7 +557,7 @@ namespace
return FTW_CONTINUE;
}
if (Util::startsWith(fpath, childRootForGCDAFiles))
if (fpath.starts_with(childRootForGCDAFiles))
{
LOG_TRC("nftw: Skipping childRoot subtree: " << fpath);
return FTW_SKIP_SUBTREE;

View File

@ -221,7 +221,7 @@ FieldParseState StatusLine::parse(const char* p, int64_t& len)
const int versionMaj = version[VersionMajPos] - '0';
const int versionMin = version[VersionMinPos] - '0';
// Version may not be null-terminated.
if (!Util::startsWith(std::string(version, VersionLen), "HTTP/") ||
if (!std::string(version, VersionLen).starts_with("HTTP/") ||
(versionMaj < 0 || versionMaj > 9) || version[VersionDotPos] != '.' ||
(versionMin < 0 || versionMin > 9) || !isWhitespace(version[VersionBreakPos]))
{
@ -359,7 +359,7 @@ int64_t Request::readData(const char* p, const int64_t len)
const int versionMaj = version[VersionMajPos] - '0';
const int versionMin = version[VersionMinPos] - '0';
// Version may not be null-terminated.
if (!Util::startsWith(std::string(version, VersionLen), "HTTP/") ||
if (!std::string(version, VersionLen).starts_with("HTTP/") ||
(versionMaj < 0 || versionMaj > 9) || version[VersionDotPos] != '.' ||
(versionMin < 0 || versionMin > 9) || !isWhitespace(version[VersionBreakPos]))
{

View File

@ -99,14 +99,14 @@ public:
}
const std::string lowerScheme = Util::toLower(scheme);
if (!Util::startsWith(lowerScheme, "http") && !Util::startsWith(lowerScheme, "ws"))
if (!lowerScheme.starts_with("http") && !lowerScheme.starts_with("ws"))
{
LOG_ERR_S("Unsupported scheme in URI while creating WebSocketSession: " << uri);
return nullptr;
}
const bool secure
= Util::startsWith(lowerScheme, "https") || Util::startsWith(lowerScheme, "wss");
= lowerScheme.starts_with("https") || lowerScheme.starts_with("wss");
const int portInt = port.empty() ? 0 : std::stoi(port);
return create(host, secure ? Protocol::HttpSsl : Protocol::HttpUnencrypted, portInt);

View File

@ -86,7 +86,7 @@ private:
if (request.getVerb() == http::Request::VERB_GET)
{
// Return test data.
if (Util::startsWith(request.getUrl(), "/status/"))
if (request.getUrl().starts_with("/status/"))
{
const auto statusCode
= Util::i32FromString(request.getUrl().substr(sizeof("/status")));
@ -120,7 +120,7 @@ private:
{
// Don't send anything back.
}
else if (Util::startsWith(request.getUrl(), "/inject"))
else if (request.getUrl().starts_with("/inject"))
{
// /inject/<hex data> sends back the data (in binary form)
// verbatim. It doesn't add headers or anything at all.
@ -133,9 +133,9 @@ private:
else
{
http::Response response(http::StatusCode::OK, fd);
if (Util::startsWith(request.getUrl(), "/echo/"))
if (request.getUrl().starts_with("/echo/"))
{
if (Util::startsWith(request.getUrl(), "/echo/chunked/"))
if (request.getUrl().starts_with("/echo/chunked/"))
{
response.set("transfer-encoding", "chunked");
std::string body = request.getUrl().substr(sizeof("/echo/chunked"));

View File

@ -172,7 +172,7 @@ public:
// We expect this to happen only with the disonnection test,
// because only in that case there is no user input.
LOK_ASSERT_MESSAGE("Expected reason to be 'Data-loss detected'",
Util::startsWith(reason, "Data-loss detected"));
reason.starts_with("Data-loss detected"));
LOK_ASSERT_MESSAGE("Expected to be in Phase::WaitDocClose but was " + toString(_phase),
_phase == Phase::WaitDocClose);
_unloadingModifiedDocDetected = true;

View File

@ -123,8 +123,8 @@ UnitBase::TestResult UnitSession::testHandshake()
wsSession->poll(
[&](const std::vector<char>& message)
{
const std::string msg = Util::toString(message);
if (!Util::startsWith(msg, "error:"))
const std::string msg(std::string(message.begin(), message.end()));
if (!msg.starts_with("error:"))
{
LOK_ASSERT_EQUAL(expectedStr, msg);
}

View File

@ -56,7 +56,7 @@ void UnitTiffLoad::invokeWSDTest()
// broken.
const std::string content
= helpers::assertResponseString(socket, "shapeselectioncontent:", testname);
LOK_ASSERT(Util::startsWith(content, "shapeselectioncontent:\n"));
LOK_ASSERT(content.starts_with("shapeselectioncontent:\n"));
exitTest(TestResult::Ok);
}

View File

@ -41,7 +41,7 @@ void testStateChanged(const std::string& filename, std::set<std::string>& comman
[&](const std::string& msg)
{
Poco::RegularExpression::MatchVec matches;
if (Util::startsWith(msg, "statechanged: {"))
if (msg.starts_with("statechanged: {"))
{
// Payload is JSON, the commandName key has the command name.
Poco::JSON::Parser parser;

View File

@ -167,7 +167,7 @@ public:
// We expect this to happen only with the disonnection test,
// because only in that case there is no user input.
LOK_ASSERT_MESSAGE("Expected reason to be 'Data-loss detected'",
Util::startsWith(reason, "Data-loss detected"));
reason.starts_with("Data-loss detected"));
LOK_ASSERT_MESSAGE("Expected to be in Phase::WaitDocClose but was " + toString(_phase),
_phase == Phase::WaitDocClose);
_unloadingModifiedDocDetected = true;
@ -252,7 +252,7 @@ public:
// no upload attempts with expired tockens. And we
// only have one session.
LOK_ASSERT_MESSAGE("Expected reason to be 'Data-loss detected'",
Util::startsWith(reason, "Data-loss detected"));
reason.starts_with("Data-loss detected"));
LOK_ASSERT_MESSAGE("Expected to be in Phase::WaitDocClose but was " + toString(_phase),
_phase == Phase::Done);
@ -376,7 +376,7 @@ public:
// We expect this to happen, since we can't upload the document.
LOK_ASSERT_MESSAGE("Expected reason to be 'Data-loss detected'",
Util::startsWith(reason, "Data-loss detected"));
reason.starts_with("Data-loss detected"));
failTest("Data-loss detected");

View File

@ -143,7 +143,7 @@ public:
{
const std::string message(data, len);
if (Util::startsWith(message, "cellformula:"))
if (message.starts_with("cellformula:"))
{
if (_currentUserId == 0)
{
@ -270,7 +270,7 @@ public:
{
const std::string message(data, len);
if (Util::startsWith(message, "cellformula:"))
if (message.starts_with("cellformula:"))
{
if (_currentUserId == 0)
{

View File

@ -271,7 +271,7 @@ public:
// We expect this to happen only with the disonnection test,
// because only in that case there is no user input.
LOK_ASSERT_MESSAGE("Expected reason to be 'Data-loss detected'",
Util::startsWith(reason, "Data-loss detected"));
reason.starts_with("Data-loss detected"));
LOK_ASSERT_MESSAGE("Expected to be in Phase::WaitDocClose but was " + toString(_phase),
_phase == Phase::WaitDocClose);
// In SaveOverwrite, we should not be in modified state, because we do save

View File

@ -1146,14 +1146,6 @@ void WhiteBoxTests::testStringCompare()
LOK_ASSERT(!Util::iequal("abc", "abcd"));
LOK_ASSERT(!Util::iequal("abc", 3, "abcd", 4));
LOK_ASSERT(!Util::startsWith("abc", "abcd"));
LOK_ASSERT(Util::startsWith("abcd", "abc"));
LOK_ASSERT(Util::startsWith("abcd", "abcd"));
LOK_ASSERT(!Util::endsWith("abc", "abcd"));
LOK_ASSERT(Util::endsWith("abcd", "bcd"));
LOK_ASSERT(Util::endsWith("abcd", "abcd"));
}
void WhiteBoxTests::testParseUri()

View File

@ -108,7 +108,7 @@ protected:
LOG_TST("WopiTestServer created with " << data.size() << " bytes from file ["
<< filenameOrContents << "]");
_filename = filenameOrContents; // Capture the real filename.
setFileContent(Util::toString(data));
setFileContent(std::string(data.begin(), data.end()));
}
else
{
@ -219,7 +219,7 @@ protected:
/// Given a wopi URI, extracts the filename.
static std::string extractFilenameFromWopiUri(const std::string& uriPath)
{
if (Util::startsWith(uriPath, getURIRootPath()))
if (uriPath.starts_with(getURIRootPath()))
{
const auto first = getURIRootPath().size();
const auto it = uriPath.find_first_of('/', first);
@ -232,13 +232,13 @@ protected:
/// Returns true iff @uriPath is a Wopi path but not to the contents.
static bool isWopiInfoRequest(const std::string& uriPath)
{
return Util::startsWith(uriPath, getURIRootPath()) && !Util::endsWith(uriPath, "/contents");
return uriPath.starts_with(getURIRootPath()) && !uriPath.ends_with("/contents");
}
/// Returns true iff @uriPath is a Wopi path to the contents of a file.
static bool isWopiContentRequest(const std::string& uriPath)
{
return Util::startsWith(uriPath, getURIRootPath()) && Util::endsWith(uriPath, "/contents");
return uriPath.starts_with(getURIRootPath()) && uriPath.ends_with("/contents");
}
void configure(Poco::Util::LayeredConfiguration& config) override
@ -478,7 +478,7 @@ protected:
LOG_TST("FakeWOPIHost: Writing document contents in storage (" << size << "bytes)");
std::vector<char> buffer(size);
message.read(buffer.data(), size);
setFileContent(Util::toString(buffer));
setFileContent(std::string(buffer.begin(), buffer.end()));
}
if (response)
@ -554,7 +554,7 @@ protected:
{
return handleHttpPostRequest(request, message, socket);
}
else if (!Util::startsWith(uriReq.getPath(), "/cool/")) // Skip requests to the websrv.
else if (!uriReq.getPath().starts_with("/cool/")) // Skip requests to the websrv.
{
// Complain if we are expected to handle something that we don't.
LOG_TST("ERROR: FakeWOPIHost: Request, cannot handle request: " << uriReq.getPath());

View File

@ -553,7 +553,7 @@ void ClientRequestDispatcher::handleIncomingMessage(SocketDisposition& dispositi
const auto pos = uri.find(ProxyRemoteStatic);
if (pos != std::string::npos)
{
if (Util::endsWith(uri, "lokit-extra-img.svg"))
if (uri.ends_with("lokit-extra-img.svg"))
{
ProxyRequestHandler::handleRequest(uri.substr(pos + ProxyRemoteLen), socket,
ProxyRequestHandler::getProxyRatingServer());

View File

@ -1453,7 +1453,7 @@ bool ClientSession::sendCombinedTiles(const char* /*buffer*/, int /*length*/, co
bool ClientSession::forwardToChild(const std::string& message,
const std::shared_ptr<DocumentBroker>& docBroker)
{
const bool binary = Util::startsWith(message, "paste") || Util::startsWith(message, "urp");
const bool binary = message.starts_with("paste") || message.starts_with("urp");
return docBroker->forwardToChild(client_from_this(), message, binary);
}

View File

@ -3397,7 +3397,7 @@ void DocumentBroker::handleMediaRequest(std::string range,
LOG_ASSERT(JsonUtil::getJSONValue<std::string>(object, "id") == tag);
const std::string url = JsonUtil::getJSONValue<std::string>(object, "url");
LOG_ASSERT(!url.empty());
if (Util::startsWith(Util::toLower(url), "file://"))
if (Util::toLower(url).starts_with("file://"))
{
// For now, we only support file:// schemes.
// In the future, we may/should support http.
@ -3656,7 +3656,7 @@ bool DocumentBroker::forwardUrpToChild(const std::string& message)
bool DocumentBroker::forwardToChild(const std::shared_ptr<ClientSession>& session,
const std::string& message, bool binary)
{
if (Util::startsWith(message, "urp "))
if (message.starts_with("urp "))
return forwardUrpToChild(message);
ASSERT_CORRECT_THREAD();
@ -3678,12 +3678,12 @@ bool DocumentBroker::forwardToChild(const std::shared_ptr<ClientSession>& sessio
LOG_TRC("Forwarding payload to child [" << viewId << "]: " << getAbbreviatedMessage(message));
#if 0 // extreme paste debugging - message can be giant and binary
if (Log::traceEnabled() && Util::startsWith(message, "paste "))
if (Log::traceEnabled() && message.starts_with("paste "))
LOG_TRC("Logging paste payload (" << message.size() << " bytes) '" << message << "' end paste");
#endif
std::string msg = "child-" + viewId + ' ';
if (Util::startsWith(message, "load "))
if (message.starts_with("load "))
{
// Special-case loading.
const StringVector tokens = StringVector::tokenize(message);

View File

@ -381,7 +381,7 @@ bool FileServerRequestHandler::isAdminLoggedIn(const HTTPRequest& request, http:
const std::string prefix = "/wopi/files";
const std::string suffix = "/contents";
std::string localPath;
if (Util::endsWith(path.toString(), suffix))
if (path.toString().ends_with(suffix))
{
localPath = path.toString().substr(prefix.length(), path.toString().length() - prefix.length() - suffix.length());
}
@ -396,7 +396,7 @@ bool FileServerRequestHandler::isAdminLoggedIn(const HTTPRequest& request, http:
throw BadRequestException("Invalid URI: " + localPath);
}
if (request.getMethod() == "GET" && !Util::endsWith(path.toString(), suffix))
if (request.getMethod() == "GET" && !path.toString().ends_with(suffix))
{
std::shared_ptr<LocalFileInfo> localFile =
LocalFileInfo::getOrCreateFile(localPath, path.getFileName());
@ -430,7 +430,7 @@ bool FileServerRequestHandler::isAdminLoggedIn(const HTTPRequest& request, http:
return;
}
else if(request.getMethod() == "GET" && Util::endsWith(path.toString(), suffix))
else if(request.getMethod() == "GET" && path.toString().ends_with(suffix))
{
std::shared_ptr<LocalFileInfo> localFile =
LocalFileInfo::getOrCreateFile(localPath,path.getFileName());
@ -444,7 +444,7 @@ bool FileServerRequestHandler::isAdminLoggedIn(const HTTPRequest& request, http:
socket->send(httpResponse);
return;
}
else if (request.getMethod() == "POST" && Util::endsWith(path.toString(), suffix))
else if (request.getMethod() == "POST" && path.toString().ends_with(suffix))
{
std::shared_ptr<LocalFileInfo> localFile =
LocalFileInfo::getOrCreateFile(localPath,path.getFileName());
@ -542,7 +542,7 @@ void FileServerRequestHandler::handleRequest(const HTTPRequest& request,
config.getString("ver_suffix", "") + "\"";
#if ENABLE_DEBUG
if (Util::startsWith(relPath, std::string("/wopi/files"))) {
if (relPath.starts_with("/wopi/files")) {
handleWopiRequest(request, requestDetails, message, socket);
return;
}
@ -823,7 +823,7 @@ void FileServerRequestHandler::readDirToHash(const std::string &basePath, const
if (S_ISDIR(fileStat.st_mode))
readDirToHash(basePath, relPath);
else if (S_ISREG(fileStat.st_mode) && Util::endsWith(relPath, ".br"))
else if (S_ISREG(fileStat.st_mode) && relPath.ends_with(".br"))
{
// Only cache without compressing.
fileCount++;

View File

@ -286,7 +286,7 @@ std::string FileServerRequestHandler::uiDefaultsToJSON(const std::string& uiDefa
currentDef = &presentationDefs;
key = keyValue[0].substr(12);
}
else if (Util::startsWith(keyValue[0], "Drawing"))
else if (keyValue[0].starts_with("Drawing"))
{
currentDef = &drawingDefs;
key = keyValue[0].substr(7);

View File

@ -55,7 +55,7 @@ std::map<std::string, std::string> getParams(const std::string& uri)
RequestDetails::RequestDetails(Poco::Net::HTTPRequest &request, const std::string& serviceRoot)
{
// Check and remove the ServiceRoot from the request.getURI()
if (!Util::startsWith(request.getURI(), serviceRoot))
if (!request.getURI().starts_with(serviceRoot))
throw BadRequestException("The request does not start with prefix: " + serviceRoot);
// re-writes ServiceRoot out of request

View File

@ -198,7 +198,7 @@ bool isTemplate(const std::string& filename)
{
std::vector<std::string> templateExtensions {".stw", ".ott", ".dot", ".dotx", ".dotm", ".otm", ".stc", ".ots", ".xltx", ".xltm", ".sti", ".otp", ".potx", ".potm", ".std", ".otg"};
for (auto & extension : templateExtensions)
if (Util::endsWith(filename, extension))
if (filename.ends_with(extension))
return true;
return false;
}
@ -861,7 +861,7 @@ WopiStorage::WOPIFileInfo::WOPIFileInfo(const FileInfo& fileInfo,
JsonUtil::findJSONValue(object, "FileUrl", _fileUrl);
// Update the scheme to https if ssl or ssl termination is on
if (Util::startsWith(_postMessageOrigin, "http://") &&
if (_postMessageOrigin.starts_with("http://") &&
(COOLWSD::isSSLEnabled() || COOLWSD::isSSLTermination()))
{
_postMessageOrigin.replace(0, 4, "https");

View File

@ -22,7 +22,7 @@
void WopiProxy::handleRequest([[maybe_unused]] SocketPoll& poll, SocketDisposition& disposition)
{
std::string url = _requestDetails.getDocumentURI();
if (Util::startsWith(url, "/wasm/"))
if (url.starts_with("/wasm/"))
{
url = url.substr(6);
}