Skip to content

Commit

Permalink
sstring: implement push_back()
Browse files Browse the repository at this point in the history
to be more compatible with basic_string<>
this is also what we expect from a sequence-alike STL containers.

Fixes scylladb#2104
Signed-off-by: Kefu Chai <kefu.chai@scylladb.com>
  • Loading branch information
tchaikov committed Feb 17, 2024
1 parent b858234 commit 9ca6163
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
23 changes: 23 additions & 0 deletions include/seastar/core/sstring.hh
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,29 @@ public:
return *this;
}

/**
* Append the given character to the end of the string
* @param ch The character to append
* @note unlike @c std::basic_string, sstring does not preallocate, so
* this call always lead to reallocation if external storage is
* used.
*/
constexpr void push_back(char_type ch) {
if (is_internal()) {
if (static_cast<Size>(u.internal.size) < max_size) {
u.internal.str[u.internal.size++] = ch;
if (NulTerminate) {
u.internal.str[u.internal.size] = '\0';
}
return;
}
}
basic_sstring new_str(initialized_later(), u.external.size + 1);
std::copy(begin(), end(), new_str.begin());
new_str.u.external.str[new_str.u.external.size - 1] = ch;
*this = std::move(new_str);
}

/**
* Resize string and use the specified @c op to modify the content and the length
* @param n new size
Expand Down
21 changes: 21 additions & 0 deletions tests/unit/sstring_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,27 @@ BOOST_AUTO_TEST_CASE(test_append) {
BOOST_REQUIRE_EQUAL(sstring("aba").append("1234", 0), "aba");
}

BOOST_AUTO_TEST_CASE(test_push_back) {
{
// append in internal storage
basic_sstring<char, uint32_t, 15> s("0123456789");
s.push_back('a');
BOOST_REQUIRE_EQUAL(s, "0123456789a");
}
{
// append causing spilling to external storage
basic_sstring<char, uint32_t, 15> s("0123456789abcde");
s.push_back('f');
BOOST_REQUIRE_EQUAL(s, "0123456789abcdef");
}
{
// append with external storage
basic_sstring<char, uint32_t, 15> s("0123456789abcdef");
s.push_back('g');
BOOST_REQUIRE_EQUAL(s, "0123456789abcdefg");
}
}

BOOST_AUTO_TEST_CASE(test_replace) {
BOOST_REQUIRE_EQUAL(sstring("abc").replace(1,1, "xyz", 1), "axc");
BOOST_REQUIRE_EQUAL(sstring("abc").replace(3,2, "xyz", 2), "abcxy");
Expand Down

0 comments on commit 9ca6163

Please sign in to comment.