Skip to content

Commit bf20b80

Browse files
committed
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.
1 parent 9271183 commit bf20b80

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

include/boost/static_string/static_string.hpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2314,6 +2314,23 @@ class basic_static_string
23142314
return N;
23152315
}
23162316

2317+
/** Return the number of additional characters that can be stored.
2318+
2319+
Returns `max_size() - size()`, i.e. the number of characters
2320+
that can still be inserted before the string reaches its
2321+
capacity.
2322+
2323+
@par Complexity
2324+
2325+
Constant.
2326+
*/
2327+
BOOST_STATIC_STRING_CPP11_CONSTEXPR
2328+
size_type
2329+
available() const noexcept
2330+
{
2331+
return max_size() - size();
2332+
}
2333+
23172334
/** Increase the capacity.
23182335
23192336
This function has no effect.

test/static_string.cpp

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -989,6 +989,29 @@ testCapacity()
989989
BOOST_TEST(static_string<3>{"abc"}.max_size() == 3);
990990
BOOST_TEST(static_string<5>{"abc"}.max_size() == 5);
991991

992+
// available()
993+
BOOST_TEST(static_string<0>{}.available() == 0);
994+
BOOST_TEST(static_string<1>{}.available() == 1);
995+
BOOST_TEST(static_string<1>{"a"}.available() == 0);
996+
BOOST_TEST(static_string<3>{"abc"}.available() == 0);
997+
BOOST_TEST(static_string<5>{"abc"}.available() == 2);
998+
BOOST_TEST(static_string<5>{}.available() == 5);
999+
{
1000+
static_string<8> s("hi");
1001+
BOOST_TEST(s.available() == 6);
1002+
s.append(" there");
1003+
BOOST_TEST(s.available() == 0);
1004+
s.clear();
1005+
BOOST_TEST(s.available() == 8);
1006+
}
1007+
// Intended use with the pos/count-taking overloads.
1008+
{
1009+
static_string<5> s("ab");
1010+
s.append("xyzwv", 0, s.available());
1011+
BOOST_TEST(s == "abxyz");
1012+
BOOST_TEST(s.available() == 0);
1013+
}
1014+
9921015
// reserve(std::size_t n)
9931016
static_string<3>{}.reserve(0);
9941017
static_string<3>{}.reserve(1);

0 commit comments

Comments
 (0)