From d136a5f54ceff2c6328235fbc477ab9107da4763 Mon Sep 17 00:00:00 2001 From: Sergio Date: Tue, 22 Nov 2022 22:55:59 +0100 Subject: [PATCH] COMMON: fix String::rfind for default value of pos (max value of size_t) --- common/str.cpp | 12 +++++++++--- test/common/str.h | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/common/str.cpp b/common/str.cpp index cbd87bbdc9c..9994f209b32 100644 --- a/common/str.cpp +++ b/common/str.cpp @@ -325,9 +325,15 @@ size_t String::rfind(const char *s) const { } size_t String::rfind(char c, size_t pos) const { - for (int idx = MIN((int)_size - 1, (int)pos); idx >= 0; --idx) { - if ((*this)[idx] == c) - return idx; + if (pos == npos || pos > _size) + pos = _size; + else + ++pos; + + while (pos > 0) { + --pos; + if ((*this)[pos] == c) + return pos; } return npos; diff --git a/test/common/str.h b/test/common/str.h index 9321f38bd72..a3952927659 100644 --- a/test/common/str.h +++ b/test/common/str.h @@ -570,6 +570,22 @@ class StringTestSuite : public CxxTest::TestSuite TS_ASSERT_EQUALS(s4, "TestTestTestTestTestTestTestTestTestTestTest"); } + void test_find() { + Common::String a("0123012"), b; + + TS_ASSERT_EQUALS(a.find('1'), 1u); + TS_ASSERT_EQUALS(a.find('3'), 3u); + TS_ASSERT_EQUALS(a.find('1', 3), 5u); + TS_ASSERT_EQUALS(b.find('*'), Common::String::npos); + TS_ASSERT_EQUALS(b.find('*', 1), Common::String::npos); + + TS_ASSERT_EQUALS(a.rfind('1'), 5u); + TS_ASSERT_EQUALS(a.rfind('3'), 3u); + TS_ASSERT_EQUALS(a.rfind('1', 3), 1u); + TS_ASSERT_EQUALS(b.rfind('*'), Common::String::npos); + TS_ASSERT_EQUALS(b.rfind('*', 1), Common::String::npos); + } + void test_setChar() { Common::String testString("123456"); testString.setChar('2', 0);