From 1cb047079aa2c26a8159d100348b7e69a49bc117 Mon Sep 17 00:00:00 2001 From: David Kalnischkies Date: Fri, 12 Aug 2016 09:07:59 +0200 Subject: don't perform int #include #include +#include #include @@ -321,19 +322,14 @@ std::string PackageManagerFancy::GetTextProgressStr(float Percent, int OutputSize) { std::string output; - int i; - - // should we raise a exception here instead? - if (Percent < 0.0 || Percent > 1.0 || OutputSize < 3) + if (unlikely(OutputSize < 3)) return output; - - int BarSize = OutputSize - 2; // bar without the leading "[" and trailing "]" - output += "["; - for(i=0; i < BarSize*Percent; i++) - output += "#"; - for (/*nothing*/; i < BarSize; i++) - output += "."; - output += "]"; + + int const BarSize = OutputSize - 2; // bar without the leading "[" and trailing "]" + int const BarDone = std::max(0, std::min(BarSize, static_cast(std::floor(Percent * BarSize)))); + output.append("["); + std::fill_n(std::fill_n(std::back_inserter(output), BarDone, '#'), BarSize - BarDone, '.'); + output.append("]"); return output; } diff --git a/test/libapt/install_progress_test.cc b/test/libapt/install_progress_test.cc index a70fc9261..b63b4716f 100644 --- a/test/libapt/install_progress_test.cc +++ b/test/libapt/install_progress_test.cc @@ -12,9 +12,14 @@ TEST(InstallProgressTest, FancyGetTextProgressStr) EXPECT_EQ(60, p.GetTextProgressStr(0.5, 60).size()); EXPECT_EQ("[#.]", p.GetTextProgressStr(0.5, 4)); + EXPECT_EQ("[..........]", p.GetTextProgressStr(0.0, 12)); EXPECT_EQ("[#.........]", p.GetTextProgressStr(0.1, 12)); + EXPECT_EQ("[####......]", p.GetTextProgressStr(0.4999, 12)); + EXPECT_EQ("[#####.....]", p.GetTextProgressStr(0.5001, 12)); EXPECT_EQ("[#########.]", p.GetTextProgressStr(0.9, 12)); + EXPECT_EQ("[##########]", p.GetTextProgressStr(1.0, 12)); // deal with incorrect inputs gracefully (or should we die instead?) - EXPECT_EQ("", p.GetTextProgressStr(-999, 12)); + EXPECT_EQ("[..........]", p.GetTextProgressStr(-1.0, 12)); + EXPECT_EQ("[##########]", p.GetTextProgressStr(2.0, 12)); } -- cgit v1.2.3