From 82a1600d3a8d4e10f120628789c14750f5ed27a2 Mon Sep 17 00:00:00 2001 From: Wiebe Cazemier Date: Sat, 23 Mar 2024 21:44:56 +0100 Subject: [PATCH] Faster implementation of startsWith() for strings --- FlashMQTests/maintests.cpp | 2 ++ FlashMQTests/maintests.h | 2 ++ FlashMQTests/tst_maintests.cpp | 12 +++++++++++- utils.cpp | 12 +++++++++++- 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/FlashMQTests/maintests.cpp b/FlashMQTests/maintests.cpp index 4290261b..83ae4d36 100644 --- a/FlashMQTests/maintests.cpp +++ b/FlashMQTests/maintests.cpp @@ -283,6 +283,8 @@ MainTests::MainTests() REGISTER_FUNCTION(testWebsocketHugePing); REGISTER_FUNCTION(testWebsocketManyBigPingFrames); REGISTER_FUNCTION(testWebsocketClose); + REGISTER_FUNCTION(testStartsWith); + } bool MainTests::test(const std::vector &tests) diff --git a/FlashMQTests/maintests.h b/FlashMQTests/maintests.h index 34318270..d5cb6927 100644 --- a/FlashMQTests/maintests.h +++ b/FlashMQTests/maintests.h @@ -203,6 +203,8 @@ class MainTests void testWebsocketManyBigPingFrames(); void testWebsocketClose(); + void testStartsWith(); + public: MainTests(); diff --git a/FlashMQTests/tst_maintests.cpp b/FlashMQTests/tst_maintests.cpp index 6261c159..62167c65 100644 --- a/FlashMQTests/tst_maintests.cpp +++ b/FlashMQTests/tst_maintests.cpp @@ -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")); +} diff --git a/utils.cpp b/utils.cpp index 24b5f8fd..451dc37c 100644 --- a/utils.cpp +++ b/utils.cpp @@ -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)