1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <inttypes.h>
18 #include <stdio.h>
19 #include <stdint.h>
20 #include <stdlib.h>
21 
22 #include <string>
23 
24 #include "utils.h"
25 
Round(int n)26 int Round(int n) {
27   int base = 1;
28   while (base*10 < n) {
29     base *= 10;
30   }
31   if (n < 2*base) {
32     return 2*base;
33   }
34   if (n < 5*base) {
35     return 5*base;
36   }
37   return 10*base;
38 }
39 
40 // Similar to the code in art, but supporting both binary and decimal prefixes.
PrettyInt(long value,size_t base)41 std::string PrettyInt(long value, size_t base) {
42   if (base != 2 && base != 10) abort();
43 
44   uint64_t count = static_cast<uint64_t>(value);
45   bool negative_number = false;
46   if (value < 0) {
47     negative_number = true;
48     count = static_cast<uint64_t>(-value);
49   }
50 
51   // The byte thresholds at which we display amounts. A count is displayed
52   // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
53   static const uint64_t kUnitThresholds2[] = {
54     1024*1024*1024 /* Gi */, 2*1024*1024 /* Mi */, 3*1024 /* Ki */, 0,
55   };
56   static const uint64_t kUnitThresholds10[] = {
57     1000*1000*1000 /* G */, 2*1000*1000 /* M */, 3*1000 /* k */, 0,
58   };
59   static const uint64_t kAmountPerUnit2[] = { 1024*1024*1024, 1024*1024, 1024, 1 };
60   static const uint64_t kAmountPerUnit10[] = { 1000*1000*1000, 1000*1000, 1000, 1 };
61   static const char* const kUnitStrings2[] = { "Gi", "Mi", "Ki", "" };
62   static const char* const kUnitStrings10[] = { "G", "M", "k", "" };
63 
64   // Which set are we using?
65   const uint64_t* kUnitThresholds = ((base == 2) ? kUnitThresholds2 : kUnitThresholds10);
66   const uint64_t* kAmountPerUnit = ((base == 2) ? kAmountPerUnit2 : kAmountPerUnit10);
67   const char* const* kUnitStrings = ((base == 2) ? kUnitStrings2 : kUnitStrings10);
68 
69   size_t i = 0;
70   for (; kUnitThresholds[i] != 0; ++i) {
71     if (count >= kUnitThresholds[i]) {
72       break;
73     }
74   }
75   char* s = NULL;
76   asprintf(&s, "%s%" PRId64 "%s", (negative_number ? "-" : ""),
77            count / kAmountPerUnit[i], kUnitStrings[i]);
78   std::string result(s);
79   free(s);
80   return result;
81 }
82