From 0a03aa949bef07554be809abfdae855e62ffde41 Mon Sep 17 00:00:00 2001 From: Roland Conybeare Date: Thu, 18 Apr 2024 13:27:06 -0400 Subject: [PATCH] xo-flatstring: undercap flastring_concat instead of char arrays --- example/ex1/ex1.cpp | 6 +++--- include/xo/flatstring/flatstring.hpp | 13 ++++++++++++- utest/flatstring.test.cpp | 19 +++++++++++++++++++ 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/example/ex1/ex1.cpp b/example/ex1/ex1.cpp index f5843db..7f46f43 100644 --- a/example/ex1/ex1.cpp +++ b/example/ex1/ex1.cpp @@ -136,12 +136,12 @@ main() { static_assert(sizeof(s14) == 7); constexpr flatstring s15 = flatstring_concat(flatstring("hello"), - ", ", - flatstring("world")); + flatstring(", "), + flatstring("world")); static_assert(s15.fixed_capacity == 13); static_assert(sizeof(s15) == 13); - constexpr auto s16 = xo::flatstring_concat("foo", "bar"); + constexpr auto s16 = xo::flatstring_concat(flatstring("foo"), flatstring("bar")); static_assert(s16.fixed_capacity == 7); diff --git a/include/xo/flatstring/flatstring.hpp b/include/xo/flatstring/flatstring.hpp index e723349..49db346 100644 --- a/include/xo/flatstring/flatstring.hpp +++ b/include/xo/flatstring/flatstring.hpp @@ -452,7 +452,18 @@ namespace xo { std::size_t pos = 0; auto detail_concat = [ &pos, &result ](auto && arg) { - constexpr auto count = (sizeof(arg) - sizeof(value_type)) / sizeof(value_type); + /* tradeoff here: + * 1. flatstring::size() is constexpr, so we can concat strings with size() < capacity(). + * (note flatstring::from_int() likely creates such strings) + * 2. ..but no size() method on char arrays. + * 3. std::size() not suitable: size of char array includes null terminator, + * while flatstring.size() excludes it, and flatstring behavior is consistent with + * std::string.size() + * Consequence of using arg.size() here; have to wrap char arrays with + * flatstring() to use them with flatstring_concat() + */ + auto count = arg.size(); + //constexpr auto count = (sizeof(arg) - sizeof(value_type)) / sizeof(value_type); std::copy_n(/*arg.c_str()*/ static_cast(arg), count, result.value_ + pos); pos += count; diff --git a/utest/flatstring.test.cpp b/utest/flatstring.test.cpp index 197ccfd..8a3761a 100644 --- a/utest/flatstring.test.cpp +++ b/utest/flatstring.test.cpp @@ -231,6 +231,25 @@ namespace xo { REQUIRE(::strcmp(concat.c_str(), req_str.c_str()) == 0); } + +#ifdef NOT_USING + { + auto concat4 = flatstring_concat(str, + flatstring(text2), + str, + flatstring(text2)); + auto req_str = string(text) + string(text2) + string(text) + string(text2); + + REQUIRE(::strcmp(concat4.c_str(), req_str.c_str()) == 0); + } +#endif + + { + auto concat4 = flatstring_concat(str, str2, str, str2); + auto req_str = string(text) + string(text2) + string(text) + string(text2); + + REQUIRE(::strcmp(concat4.c_str(), req_str.c_str()) == 0); + } } template