Skip to content

Commit

Permalink
Do not require owning strings for startsWith.
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bbannier committed Dec 20, 2024
1 parent 7985958 commit 9a773ce
Show file tree
Hide file tree
Showing 3 changed files with 3 additions and 13 deletions.
2 changes: 1 addition & 1 deletion hilti/runtime/include/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion hilti/runtime/src/tests/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
12 changes: 1 addition & 11 deletions hilti/runtime/src/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 9a773ce

Please sign in to comment.