From bf20b809ec79f43acd4709b4a64dfae17788f061 Mon Sep 17 00:00:00 2001 From: Gennaro Prota Date: Wed, 22 Apr 2026 10:06:00 +0200 Subject: [PATCH] Add basic_static_string::available() This returns max_size() - size(), i.e. the number of characters that can still be inserted before the string reaches its capacity. Intended as a shorthand for capacity-capped writes in combination with the pos/count-taking overloads of append, assign, and insert: str.append(sv, 0, str.available()); Addresses the ergonomic complaint in issue #81 without expanding the overload set. Closes issue #81. --- include/boost/static_string/static_string.hpp | 17 ++++++++++++++ test/static_string.cpp | 23 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/include/boost/static_string/static_string.hpp b/include/boost/static_string/static_string.hpp index f82425a..f258d10 100644 --- a/include/boost/static_string/static_string.hpp +++ b/include/boost/static_string/static_string.hpp @@ -2314,6 +2314,23 @@ public: return N; } + /** Return the number of additional characters that can be stored. + + Returns `max_size() - size()`, i.e. the number of characters + that can still be inserted before the string reaches its + capacity. + + @par Complexity + + Constant. + */ + BOOST_STATIC_STRING_CPP11_CONSTEXPR + size_type + available() const noexcept + { + return max_size() - size(); + } + /** Increase the capacity. This function has no effect. diff --git a/test/static_string.cpp b/test/static_string.cpp index 6bbaee9..19a7493 100644 --- a/test/static_string.cpp +++ b/test/static_string.cpp @@ -989,6 +989,29 @@ testCapacity() BOOST_TEST(static_string<3>{"abc"}.max_size() == 3); BOOST_TEST(static_string<5>{"abc"}.max_size() == 5); + // available() + BOOST_TEST(static_string<0>{}.available() == 0); + BOOST_TEST(static_string<1>{}.available() == 1); + BOOST_TEST(static_string<1>{"a"}.available() == 0); + BOOST_TEST(static_string<3>{"abc"}.available() == 0); + BOOST_TEST(static_string<5>{"abc"}.available() == 2); + BOOST_TEST(static_string<5>{}.available() == 5); + { + static_string<8> s("hi"); + BOOST_TEST(s.available() == 6); + s.append(" there"); + BOOST_TEST(s.available() == 0); + s.clear(); + BOOST_TEST(s.available() == 8); + } + // Intended use with the pos/count-taking overloads. + { + static_string<5> s("ab"); + s.append("xyzwv", 0, s.available()); + BOOST_TEST(s == "abxyz"); + BOOST_TEST(s.available() == 0); + } + // reserve(std::size_t n) static_string<3>{}.reserve(0); static_string<3>{}.reserve(1);