Skip to content

Commit

Permalink
Faster implementation of startsWith() for strings
Browse files Browse the repository at this point in the history
  • Loading branch information
halfgaar committed Mar 23, 2024
1 parent e28e8ca commit 82a1600
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
2 changes: 2 additions & 0 deletions FlashMQTests/maintests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,8 @@ MainTests::MainTests()
REGISTER_FUNCTION(testWebsocketHugePing);
REGISTER_FUNCTION(testWebsocketManyBigPingFrames);
REGISTER_FUNCTION(testWebsocketClose);
REGISTER_FUNCTION(testStartsWith);

}

bool MainTests::test(const std::vector<std::string> &tests)
Expand Down
2 changes: 2 additions & 0 deletions FlashMQTests/maintests.h
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ class MainTests
void testWebsocketManyBigPingFrames();
void testWebsocketClose();

void testStartsWith();


public:
MainTests();
Expand Down
12 changes: 11 additions & 1 deletion FlashMQTests/tst_maintests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2831,6 +2831,16 @@ void MainTests::testTopicMatchingInSubscriptionTree()
testTopicMatchingInSubscriptionTreeHelper("+/one/+/+/", "/one/two/asdf/a", 0);
}


void MainTests::testStartsWith()
{
FMQ_VERIFY(startsWith("", ""));
FMQ_VERIFY(startsWith("a", ""));
FMQ_VERIFY(startsWith("abcd", "abc"));
FMQ_VERIFY(startsWith("a", ""));

FMQ_VERIFY(!startsWith("abc", "abcd"));
FMQ_VERIFY(!startsWith("abcd", "bcd"));
FMQ_VERIFY(!startsWith("", "a"));
}


12 changes: 11 additions & 1 deletion utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,17 @@ std::string &rtrim(std::string &s, unsigned char c)

bool startsWith(const std::string &s, const std::string &needle)
{
return s.find(needle) == 0;
if (s.length() < needle.length())
return false;

size_t i;
for (i = 0; i < needle.length(); i++)
{
if (s[i] != needle[i])
return false;
}

return i == needle.length();
}

std::string getSecureRandomString(const ssize_t len)
Expand Down

0 comments on commit 82a1600

Please sign in to comment.