From bdfb466cd26b82e76bcdccab9ad3f924add89eb5 Mon Sep 17 00:00:00 2001 From: Marco Bubke Date: Thu, 2 Feb 2017 11:56:24 +0100 Subject: [PATCH] Utils: Add replace for characters It is much more performant to have a overload of char instead of providing a string all the time. Change-Id: I1a4ed82bf056f6af0c1f91c236b3fc30afa7f5d8 Reviewed-by: Tim Jenssen --- src/libs/utils/smallstring.h | 11 +++++++++++ tests/unit/unittest/smallstring-test.cpp | 9 +++++++++ 2 files changed, 20 insertions(+) diff --git a/src/libs/utils/smallstring.h b/src/libs/utils/smallstring.h index 4cc9638109a..0a38d5ddecc 100644 --- a/src/libs/utils/smallstring.h +++ b/src/libs/utils/smallstring.h @@ -473,6 +473,17 @@ public: replaceLargerSized(fromText, toText); } + void replace(char fromCharacter, char toCharacter) + { + reserve(size()); + + auto operation = [=] (char currentCharacter) { + return currentCharacter == fromCharacter ? toCharacter : currentCharacter; + }; + + std::transform(begin(), end(), begin(), operation); + } + void replace(size_type position, size_type length, SmallStringView replacementText) { size_type newSize = size() - length + replacementText.size(); diff --git a/tests/unit/unittest/smallstring-test.cpp b/tests/unit/unittest/smallstring-test.cpp index f9a8289f673..29c40635421 100644 --- a/tests/unit/unittest/smallstring-test.cpp +++ b/tests/unit/unittest/smallstring-test.cpp @@ -747,6 +747,15 @@ TEST(SmallString, Clear) ASSERT_TRUE(text.isEmpty()); } +TEST(SmallString, ReplaceWithCharacter) +{ + SmallString text("here is some text, here is some text, here is some text"); + + text.replace('s', 'x'); + + ASSERT_THAT(text, SmallString("here ix xome text, here ix xome text, here ix xome text")); +} + TEST(SmallString, ReplaceWithEqualSizedText) { SmallString text("here is some text");