From b8e391e5f0a66bc61eaf6feb85492b588058dd51 Mon Sep 17 00:00:00 2001 From: Marco Bubke Date: Mon, 5 Dec 2016 12:39:59 +0100 Subject: [PATCH] Utils: Fix SmallString reserve for read only references The capacity of a real only reference is zero but the size is larger than zero. So if we reserve memory the new capacity has to be bigger than the size and the capacity. Change-Id: I8b423da7e7c1cf7cee081d1b3f3464b6fb3f67cf Reviewed-by: Tim Jenssen Reviewed-by: Tobias Hunger --- src/libs/utils/smallstring.h | 1 + tests/unit/unittest/smallstring-test.cpp | 28 +++++++++++++++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/src/libs/utils/smallstring.h b/src/libs/utils/smallstring.h index eae9c29dc46..82bf50440fe 100644 --- a/src/libs/utils/smallstring.h +++ b/src/libs/utils/smallstring.h @@ -240,6 +240,7 @@ public: m_data.allocated.data.capacity = newCapacity; } else { const size_type oldSize = size(); + newCapacity = std::max(newCapacity, oldSize); const char *oldData = data(); char *newData = Memory::allocate(newCapacity + 1); diff --git a/tests/unit/unittest/smallstring-test.cpp b/tests/unit/unittest/smallstring-test.cpp index 05925d72b6c..3bbb10c6539 100644 --- a/tests/unit/unittest/smallstring-test.cpp +++ b/tests/unit/unittest/smallstring-test.cpp @@ -815,25 +815,43 @@ TEST(SmallString, EndsWithSmallString) ASSERT_TRUE(text.endsWith('h')); } -TEST(SmallString, ReserveSmallerThanReference) +TEST(SmallString, ReserveSmallerThanShortStringCapacity) { SmallString text("text"); text.reserve(2); - ASSERT_THAT(text.capacity(), 30); + ASSERT_THAT(text.capacity(), AnyOf(30, 4)); } -TEST(SmallString, ReserveBiggerThanReference) +TEST(SmallString, ReserveSmallerThanReference) +{ + SmallString text("some very very very very very very very very very very very long string"); + + text.reserve(35); + + ASSERT_THAT(text.capacity(), 71); +} + +TEST(SmallString, ReserveBiggerThanShortStringCapacity) { SmallString text("text"); text.reserve(10); - ASSERT_THAT(text.capacity(), 30); + ASSERT_THAT(text.capacity(), AnyOf(30, 10)); } -TEST(SmallString, ReserveMuchBiggerThanReference) +TEST(SmallString, ReserveBiggerThanReference) +{ + SmallString text("some very very very very very very very very very very very long string"); + + text.reserve(35); + + ASSERT_THAT(text.capacity(), 71); +} + +TEST(SmallString, ReserveMuchBiggerThanShortStringCapacity) { SmallString text("text");