Skip to content

Commit

Permalink
fix sstring.find(): make find("") compatible with std::string
Browse files Browse the repository at this point in the history
- Fixes #1001
- add compatibility test for find()

Closes #1002
  • Loading branch information
longqimin authored and nyh committed Jan 19, 2022
1 parent 777e4b3 commit fde471f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
7 changes: 7 additions & 0 deletions include/seastar/core/sstring.hh
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,13 @@ public:
const char_type* c_str = s.str();
const char_type* c_str_end = s.str() + s.size();

if (c_str == c_str_end) {
/* see https://en.cppreference.com/w/cpp/string/basic_string/find
* - an empty substring is found at pos if and only if pos <= size()
*/
return (pos <= size()) ? pos : npos;
}

while (it < end) {
auto i = it;
auto j = c_str;
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/sstring_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,29 @@ BOOST_AUTO_TEST_CASE(test_add_literal_to_sstring) {
BOOST_AUTO_TEST_CASE(test_find_sstring) {
BOOST_REQUIRE_EQUAL(sstring("abcde").find('b'), 1u);
BOOST_REQUIRE_EQUAL(sstring("babcde").find('b',1), 2u);
BOOST_REQUIRE_EQUAL(sstring("").find("", 0), 0u);
BOOST_REQUIRE_EQUAL(sstring("").find("", 1), sstring::npos);
}

BOOST_AUTO_TEST_CASE(test_find_sstring_compatible) {
auto check_find = [](const char* s1, const char* s2, size_t pos) {
const auto xpos_ss = sstring(s1).find(s2, pos);
const auto xpos_std = std::string(s1).find(s2, pos);

// verify that std::string really has the same behavior as we just tested for sstring
if (xpos_ss == sstring::npos) { // sstring::npos may not equal std::string::npos ?
BOOST_REQUIRE_EQUAL(xpos_std, std::string::npos);
} else {
BOOST_REQUIRE_EQUAL(xpos_ss, xpos_std);
}
};

check_find("", "", 0);
check_find("", "", 1);
check_find("abcde", "", 0);
check_find("abcde", "", 1);
check_find("abcde", "", 5);
check_find("abcde", "", 6);
}

BOOST_AUTO_TEST_CASE(test_not_find_sstring) {
Expand Down

0 comments on commit fde471f

Please sign in to comment.