Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions include/boost/json/detail/impl/string_impl.ipp
Original file line number Diff line number Diff line change
Expand Up @@ -435,9 +435,10 @@ shrink_to_fit(
auto const t = p_.t;
if(t->size <= sbo_chars_)
{
char const* const p = data();
s_.k = short_string_;
std::memcpy(
s_.buf, data(), t->size);
s_.buf, p, t->size);
s_.buf[sbo_chars_] =
static_cast<char>(
sbo_chars_ - t->size);
Expand All @@ -458,7 +459,7 @@ shrink_to_fit(
std::memcpy(
tmp.data(),
data(),
size());
size() + 1);
destroy(sp);
*this = tmp;
#ifndef BOOST_NO_EXCEPTIONS
Expand Down
32 changes: 32 additions & 0 deletions test/string.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1368,6 +1368,38 @@ class string_test
s.shrink_to_fit();
BOOST_TEST(s.capacity() < cap);
});

// shrink_to_fit() preserves the contents across reallocation
{
std::size_t const sbo = string{}.capacity();

// heap -> SBO: shrink a dynamic string down to fit in the SBO
{
std::string big(sbo * 3, '\0');
std::iota(big.begin(), big.end(), 'a');
string s(big.data(), big.size());
BOOST_TEST(s.capacity() > sbo);
std::size_t const n = sbo / 2;
s.resize(n);
s.shrink_to_fit();
BOOST_TEST(s.size() == n);
BOOST_TEST(s == string_view(big.data(), n));
BOOST_TEST(s.c_str()[s.size()] == '\0');
}

// heap -> smaller heap: still larger than the SBO after shrinking
{
std::string big(sbo * 4, '\0');
std::iota(big.begin(), big.end(), 'A');
string s(big.data(), big.size());
std::size_t const n = sbo * 2;
s.resize(n);
s.shrink_to_fit();
BOOST_TEST(s.size() == n);
BOOST_TEST(s == string_view(big.data(), n));
BOOST_TEST(s.c_str()[s.size()] == '\0');
}
}
}

void
Expand Down
Loading