diff --git a/include/boost/json/detail/impl/string_impl.ipp b/include/boost/json/detail/impl/string_impl.ipp index ad75f8693..986e2c330 100644 --- a/include/boost/json/detail/impl/string_impl.ipp +++ b/include/boost/json/detail/impl/string_impl.ipp @@ -435,9 +435,9 @@ shrink_to_fit( auto const t = p_.t; if(t->size <= sbo_chars_) { - s_.k = short_string_; std::memcpy( s_.buf, data(), t->size); + s_.k = short_string_; s_.buf[sbo_chars_] = static_cast( sbo_chars_ - t->size); @@ -458,7 +458,7 @@ shrink_to_fit( std::memcpy( tmp.data(), data(), - size()); + size() + 1); destroy(sp); *this = tmp; #ifndef BOOST_NO_EXCEPTIONS diff --git a/test/string.cpp b/test/string.cpp index 282cad7f4..51e234be5 100644 --- a/test/string.cpp +++ b/test/string.cpp @@ -1367,6 +1367,24 @@ class string_test s.shrink_to_fit(); BOOST_TEST(s.capacity() < cap); + + std::string const copy( s.begin(), s.end() ); + + std::size_t const sbo_capacity = string{}.capacity(); + std::size_t n = sbo_capacity + 1; + BOOST_ASSERT(s.capacity() > n); + s.resize(n); + s.shrink_to_fit(); + BOOST_TEST(s.size() == n); + BOOST_TEST(s == string_view(copy.data(), n)); + BOOST_TEST(s.data()[s.size()] == '\0'); + + n = sbo_capacity - 1; + s.resize(n); + s.shrink_to_fit(); + BOOST_TEST(s.size() == n); + BOOST_TEST(s.capacity() == sbo_capacity); + BOOST_TEST(s == string_view(copy.data(), n)); }); }