diff options
| author | Marco Bubke <[email protected]> | 2017-01-31 16:16:40 +0100 |
|---|---|---|
| committer | Marco Bubke <[email protected]> | 2017-01-31 16:06:33 +0000 |
| commit | 729c535376159f8a917e3d712d40a17d96909ecd (patch) | |
| tree | 5283a276db72071cf1a7ace33cfd774f365b980c | |
| parent | 9b4afa01a120647ca696418108f0ef427c053375 (diff) | |
Utils: Add intializer_list constructor in SmallString
You can now write
SmallString text = {"Oh ", women[4], " how much I miss you"};
if it can be casted to SmallStringView.
Change-Id: I86b69ee8d735017cac4391e7c4e68355eb5f227b
Reviewed-by: Tim Jenssen <[email protected]>
| -rw-r--r-- | src/libs/utils/smallstring.h | 24 | ||||
| -rw-r--r-- | tests/unit/unittest/smallstring-test.cpp | 42 |
2 files changed, 66 insertions, 0 deletions
diff --git a/src/libs/utils/smallstring.h b/src/libs/utils/smallstring.h index 359b5a2e81e..fd5e208ecf1 100644 --- a/src/libs/utils/smallstring.h +++ b/src/libs/utils/smallstring.h @@ -40,6 +40,8 @@ #include <cstdlib> #include <climits> #include <cstring> +#include <initializer_list> +#include <numeric> #include <string> #include <unordered_map> #include <utility> @@ -135,6 +137,28 @@ public: { } + BasicSmallString(std::initializer_list<Utils::SmallStringView> list) + { + std::size_t size = std::accumulate(list.begin(), + list.end(), + std::size_t(0), + [] (std::size_t size, Utils::SmallStringView string) { + return size + string.size(); + }); + + reserve(size); + setSize(size); + + char *currentData = data(); + + for (Utils::SmallStringView string : list) { + std::memcpy(currentData, string.data(), string.size()); + + currentData += string.size(); + } + + at(size) = 0; + } ~BasicSmallString() noexcept { diff --git a/tests/unit/unittest/smallstring-test.cpp b/tests/unit/unittest/smallstring-test.cpp index d846395c3ae..a0f2201bf7a 100644 --- a/tests/unit/unittest/smallstring-test.cpp +++ b/tests/unit/unittest/smallstring-test.cpp @@ -1186,3 +1186,45 @@ TEST(SmallString, ManipulateNonConstSubscriptOperator) ASSERT_THAT(text, SmallString{"some qext"}); } + +TEST(SmallString, EmptyInitializerListContent) +{ + SmallString text = {}; + + ASSERT_THAT(text, SmallString()); +} + +TEST(SmallString, EmptyInitializerListSize) +{ + SmallString text = {}; + + ASSERT_THAT(text, SizeIs(0)); +} + +TEST(SmallString, EmptyInitializerListNullTerminated) +{ + auto end = SmallString{{}}[0]; + + ASSERT_THAT(end, '\0'); +} + +TEST(SmallString, InitializerListContent) +{ + SmallString text = {"some", " ", "text"}; + + ASSERT_THAT(text, SmallString("some text")); +} + +TEST(SmallString, InitializerListSize) +{ + SmallString text = {"some", " ", "text"}; + + ASSERT_THAT(text, SizeIs(9)); +} + +TEST(SmallString, InitializerListNullTerminated) +{ + auto end = SmallString{"some", " ", "text"}[9]; + + ASSERT_THAT(end, '\0'); +} |
