From 04ce2ea7a2930b32655823d55a8ff9865a37d6c2 Mon Sep 17 00:00:00 2001 From: Kevin Robert Stravers Date: Tue, 24 Sep 2019 13:24:02 +0200 Subject: Ensure substring indexing never goes negative With widths lower than 4, the ElideMiddle function would crash because its substring access would wrap around and attempt to access the max size_t value. This patch fixes that. --- src/util.cc | 6 ++++++ src/util_test.cc | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/src/util.cc b/src/util.cc index 666cf9d..70096cd 100644 --- a/src/util.cc +++ b/src/util.cc @@ -596,6 +596,12 @@ double GetLoadAverage() { #endif // _WIN32 string ElideMiddle(const string& str, size_t width) { + switch (width) { + case 0: return ""; + case 1: return "."; + case 2: return ".."; + case 3: return "..."; + } const int kMargin = 3; // Space for "...". string result = str; if (result.size() > width) { diff --git a/src/util_test.cc b/src/util_test.cc index d97b48c..b43788d 100644 --- a/src/util_test.cc +++ b/src/util_test.cc @@ -420,6 +420,10 @@ TEST(ElideMiddle, NothingToElide) { string input = "Nothing to elide in this short string."; EXPECT_EQ(input, ElideMiddle(input, 80)); EXPECT_EQ(input, ElideMiddle(input, 38)); + EXPECT_EQ("", ElideMiddle(input, 0)); + EXPECT_EQ(".", ElideMiddle(input, 1)); + EXPECT_EQ("..", ElideMiddle(input, 2)); + EXPECT_EQ("...", ElideMiddle(input, 3)); } TEST(ElideMiddle, ElideInTheMiddle) { -- cgit v0.12