From 9a773cea18938cb964986244d05435b9704cf08a Mon Sep 17 00:00:00 2001 From: Benjamin Bannier Date: Fri, 20 Dec 2024 11:09:57 +0100 Subject: [PATCH] Do not require owning strings for `startsWith`. By passing in a `const std::string&` we would have incurred construction costs of an owning string when all we needed was a non-owning view. We also clean up the implementation of `startsWith` to use standard library functionality. --- hilti/runtime/include/util.h | 2 +- hilti/runtime/src/tests/util.cc | 2 +- hilti/runtime/src/util.cc | 12 +----------- 3 files changed, 3 insertions(+), 13 deletions(-) diff --git a/hilti/runtime/include/util.h b/hilti/runtime/include/util.h index 263ec46e2..0f9ee4874 100644 --- a/hilti/runtime/include/util.h +++ b/hilti/runtime/include/util.h @@ -240,7 +240,7 @@ std::string replace(std::string s, std::string_view o, std::string_view n); * * \note This function is not UTF8-aware. */ -bool startsWith(const std::string& s, const std::string& prefix); +bool startsWith(std::string_view s, std::string_view prefix); /** * Python-style enumerate() that returns an iterable yielding pairs `(index, diff --git a/hilti/runtime/src/tests/util.cc b/hilti/runtime/src/tests/util.cc index 13bce427e..9710322ba 100644 --- a/hilti/runtime/src/tests/util.cc +++ b/hilti/runtime/src/tests/util.cc @@ -148,7 +148,7 @@ TEST_CASE("createTemporaryFile") { SUBCASE("custom prefix") { auto prefix = "1234567890"; tmp = createTemporaryFile(prefix).valueOrThrow(); - CHECK(startsWith(tmp.filename(), prefix)); + CHECK(startsWith(tmp.filename().string(), prefix)); } CAPTURE(tmp); diff --git a/hilti/runtime/src/util.cc b/hilti/runtime/src/util.cc index 1f0ad0fee..946cffd8f 100644 --- a/hilti/runtime/src/util.cc +++ b/hilti/runtime/src/util.cc @@ -381,17 +381,7 @@ std::string hilti::rt::replace(std::string s, std::string_view o, std::string_vi return s; } -bool hilti::rt::startsWith(const std::string& s, const std::string& prefix) { - if ( s.size() < prefix.size() ) - return false; - - for ( size_t i = 0; i < prefix.size(); ++i ) { - if ( s[i] != prefix[i] ) - return false; - } - - return true; -} +bool hilti::rt::startsWith(std::string_view s, std::string_view prefix) { return s.substr(0, prefix.size()) == prefix; } hilti::rt::ByteOrder hilti::rt::systemByteOrder() { #ifdef LITTLE_ENDIAN