| 27 | namespace port { |
| 28 | |
| 29 | class HumanReadableNumBytes { |
| 30 | public: |
| 31 | static string ToString(int64 num_bytes) { |
| 32 | if (num_bytes == std::numeric_limits<int64>::min()) { |
| 33 | // Special case for number with not representable nagation. |
| 34 | return "-8E"; |
| 35 | } |
| 36 | |
| 37 | const char* neg_str = GetNegStr(&num_bytes); |
| 38 | |
| 39 | // Special case for bytes. |
| 40 | if (num_bytes < 1024LL) { |
| 41 | // No fractions for bytes. |
| 42 | return absl::StrFormat("%s%dB", neg_str, num_bytes); |
| 43 | } |
| 44 | |
| 45 | static const char units[] = "KMGTPE"; // int64 only goes up to E. |
| 46 | const char* unit = units; |
| 47 | while (num_bytes >= (1024LL) * (1024LL)) { |
| 48 | num_bytes /= (1024LL); |
| 49 | ++unit; |
| 50 | assert(unit < units + sizeof(units)); |
| 51 | } |
| 52 | |
| 53 | if (*unit == 'K') { |
| 54 | return absl::StrFormat("%s%.1f%c", neg_str, num_bytes / 1024.0, *unit); |
| 55 | } |
| 56 | return absl::StrFormat("%s%.2f%c", neg_str, num_bytes / 1024.0, *unit); |
| 57 | } |
| 58 | |
| 59 | private: |
| 60 | template <typename T> |
| 61 | static const char* GetNegStr(T* value) { |
| 62 | if (*value < 0) { |
| 63 | *value = -(*value); |
| 64 | return "-"; |
| 65 | } else { |
| 66 | return ""; |
| 67 | } |
| 68 | } |
| 69 | }; |
| 70 | |
| 71 | } // namespace port |
| 72 | } // namespace stream_executor |