Home | History | Annotate | Download | only in Console
      1 // PercentPrinter.cpp
      2 
      3 #include "StdAfx.h"
      4 
      5 #include "Common/IntToString.h"
      6 #include "Common/MyString.h"
      7 
      8 #include "PercentPrinter.h"
      9 
     10 const int kPaddingSize = 2;
     11 const int kPercentsSize = 4;
     12 const int kMaxExtraSize = kPaddingSize + 32 + kPercentsSize;
     13 
     14 static void ClearPrev(char *p, int num)
     15 {
     16   int i;
     17   for (i = 0; i < num; i++) *p++ = '\b';
     18   for (i = 0; i < num; i++) *p++ = ' ';
     19   for (i = 0; i < num; i++) *p++ = '\b';
     20   *p = '\0';
     21 }
     22 
     23 void CPercentPrinter::ClosePrint()
     24 {
     25   if (m_NumExtraChars == 0)
     26     return;
     27   char s[kMaxExtraSize * 3 + 1];
     28   ClearPrev(s, m_NumExtraChars);
     29   (*OutStream) << s;
     30   m_NumExtraChars = 0;
     31 }
     32 
     33 void CPercentPrinter::PrintString(const char *s)
     34 {
     35   ClosePrint();
     36   (*OutStream) << s;
     37 }
     38 
     39 void CPercentPrinter::PrintString(const wchar_t *s)
     40 {
     41   ClosePrint();
     42   (*OutStream) << s;
     43 }
     44 
     45 void CPercentPrinter::PrintNewLine()
     46 {
     47   ClosePrint();
     48   (*OutStream) << "\n";
     49 }
     50 
     51 void CPercentPrinter::RePrintRatio()
     52 {
     53   char s[32];
     54   ConvertUInt64ToString(((m_Total == 0) ? 0 : (m_CurValue * 100 / m_Total)), s);
     55   int size = (int)strlen(s);
     56   s[size++] = '%';
     57   s[size] = '\0';
     58 
     59   int extraSize = kPaddingSize + MyMax(size, kPercentsSize);
     60   if (extraSize < m_NumExtraChars)
     61     extraSize = m_NumExtraChars;
     62 
     63   char fullString[kMaxExtraSize * 3];
     64   char *p = fullString;
     65   int i;
     66   if (m_NumExtraChars == 0)
     67   {
     68     for (i = 0; i < extraSize; i++)
     69       *p++ = ' ';
     70     m_NumExtraChars = extraSize;
     71   }
     72 
     73   for (i = 0; i < m_NumExtraChars; i++)
     74     *p++ = '\b';
     75   m_NumExtraChars = extraSize;
     76   for (; size < m_NumExtraChars; size++)
     77     *p++ = ' ';
     78   MyStringCopy(p, s);
     79   (*OutStream) << fullString;
     80   OutStream->Flush();
     81   m_PrevValue = m_CurValue;
     82 }
     83 
     84 void CPercentPrinter::PrintRatio()
     85 {
     86   if (m_CurValue < m_PrevValue + m_MinStepSize &&
     87       m_CurValue + m_MinStepSize > m_PrevValue && m_NumExtraChars != 0)
     88     return;
     89   RePrintRatio();
     90 }
     91