1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.hbtop.field;
19
20 import java.math.BigDecimal;
21 import java.util.Objects;
22
23 import org.apache.hadoop.hbase.classification.InterfaceAudience;
24
25
26
27
28
29 @InterfaceAudience.Private
30 public final class Size implements Comparable<Size> {
31 public static final Size ZERO = new Size(0, Unit.KILOBYTE);
32 private static final BigDecimal SCALE_BASE = BigDecimal.valueOf(1024D);
33
34 public enum Unit {
35
36 PETABYTE(100, "PB"),
37 TERABYTE(99, "TB"),
38 GIGABYTE(98, "GB"),
39 MEGABYTE(97, "MB"),
40 KILOBYTE(96, "KB"),
41 BYTE(95, "B");
42 private final int orderOfSize;
43 private final String simpleName;
44
45 Unit(int orderOfSize, String simpleName) {
46 this.orderOfSize = orderOfSize;
47 this.simpleName = simpleName;
48 }
49
50 public int getOrderOfSize() {
51 return orderOfSize;
52 }
53
54 public String getSimpleName() {
55 return simpleName;
56 }
57 }
58
59 private final double value;
60 private final Unit unit;
61
62 public Size(double value, Unit unit) {
63 if (value < 0) {
64 throw new IllegalArgumentException("The value:" + value + " can't be negative");
65 }
66 this.value = value;
67 this.unit = unit;
68 }
69
70
71
72
73 public Unit getUnit() {
74 return unit;
75 }
76
77
78
79
80 public long getLongValue() {
81 return (long) value;
82 }
83
84
85
86
87 public double get() {
88 return value;
89 }
90
91
92
93
94
95
96
97 public double get(Unit unit) {
98 if (value == 0) {
99 return value;
100 }
101 int diff = this.unit.getOrderOfSize() - unit.getOrderOfSize();
102 if (diff == 0) {
103 return value;
104 }
105
106 BigDecimal rval = BigDecimal.valueOf(value);
107 for (int i = 0; i != Math.abs(diff); ++i) {
108 rval = diff > 0 ? rval.multiply(SCALE_BASE) : rval.divide(SCALE_BASE);
109 }
110 return rval.doubleValue();
111 }
112
113 @Override
114 public int compareTo(Size other) {
115 int diff = unit.getOrderOfSize() - other.unit.getOrderOfSize();
116 if (diff == 0) {
117 return Double.compare(value, other.value);
118 }
119
120 BigDecimal thisValue = BigDecimal.valueOf(value);
121 BigDecimal otherValue = BigDecimal.valueOf(other.value);
122 if (diff > 0) {
123 for (int i = 0; i != Math.abs(diff); ++i) {
124 thisValue = thisValue.multiply(SCALE_BASE);
125 }
126 } else {
127 for (int i = 0; i != Math.abs(diff); ++i) {
128 otherValue = otherValue.multiply(SCALE_BASE);
129 }
130 }
131 return thisValue.compareTo(otherValue);
132 }
133
134 @Override
135 public String toString() {
136 return value + unit.getSimpleName();
137 }
138
139 @Override
140 public boolean equals(Object obj) {
141 if (obj == null) {
142 return false;
143 }
144 if (obj == this) {
145 return true;
146 }
147 if (obj instanceof Size) {
148 return compareTo((Size)obj) == 0;
149 }
150 return false;
151 }
152
153 @Override
154 public int hashCode() {
155 return Objects.hash(value, unit);
156 }
157 }