format_data_size.cpp
Go to the documentation of this file.
1 // QLocale::formatDataSize backported from Qt 5.10
2 // Ported by Max Schwarz <max.schwarz@uni-bonn.de>
3 
4 #include "format_data_size.h"
5 
6 #include <cmath>
7 
8 #include <QtAlgorithms>
9 #include <QLocale>
10 
11 namespace rqt_rosmon
12 {
13 
14 static inline uint countLeadingZeroBits(quint64 v)
15 {
16  return __builtin_clzll(v);
17 }
18 
19 QString formattedDataSize(qint64 bytes, int precision)
20 {
21  int power, base = 1000;
22  if (!bytes) {
23  power = 0;
24  } else { // Compute log2(bytes) / 10:
25  power = int((63 - countLeadingZeroBits(quint64(qAbs(bytes)))) / 10);
26  base = 1024;
27  }
28 
29  QLocale locale = QLocale::system();
30 
31  // Only go to doubles if we'll be using a quantifier:
32  const QString number = power
33  ? locale.toString(bytes / std::pow(double(base), power), 'f', qMin(precision, 3 * power))
34  : locale.toString(bytes);
35 
36  // We don't support sizes in units larger than exbibytes because
37  // the number of bytes would not fit into qint64.
38  Q_ASSERT(power <= 6 && power >= 0);
39  QString unit;
40  if (power > 0) {
41  switch(power)
42  {
43  case 1: unit = "KiB"; break;
44  case 2: unit = "MiB"; break;
45  case 3: unit = "GiB"; break;
46  case 4: unit = "TiB"; break;
47  case 5: unit = "PiB"; break;
48  case 6: unit = "EiB"; break;
49  }
50  } else {
51  unit = "B";
52  }
53 
54  return number + QLatin1Char(' ') + unit;
55 }
56 
57 }
QString formattedDataSize(qint64 bytes, int precision)
static uint countLeadingZeroBits(quint64 v)


rqt_rosmon
Author(s): Max Schwarz
autogenerated on Sat Jan 9 2021 03:35:46