Fix Decimal64 using Longs.hashCode()
[yangtools.git] / yang / yang-common / src / main / java / org / opendaylight / yangtools / yang / common / Decimal64.java
1 /*
2  * Copyright (c) 2015 Pantheon Technologies s.r.o. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.common;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.annotations.VisibleForTesting;
15 import com.google.common.base.Strings;
16 import java.math.BigDecimal;
17 import org.opendaylight.yangtools.concepts.Immutable;
18
19 /**
20  * Dedicated type for YANG's 'type decimal64' type. This class is similar to {@link BigDecimal}, but provides more
21  * efficient storage, as it has fixed precision.
22  *
23  * @author Robert Varga
24  */
25 @Beta
26 public final class Decimal64 extends Number implements Comparable<Decimal64>, Immutable {
27     private static final long serialVersionUID = 1L;
28
29     private static final int MAX_FRACTION_DIGITS = 18;
30
31     private static final long[] SCALE = {
32         10,
33         100,
34         1000,
35         10000,
36         100000,
37         1000000,
38         10000000,
39         100000000,
40         1000000000,
41         10000000000L,
42         100000000000L,
43         1000000000000L,
44         10000000000000L,
45         100000000000000L,
46         1000000000000000L,
47         10000000000000000L,
48         100000000000000000L,
49         1000000000000000000L
50     };
51
52     static {
53         verify(SCALE.length == MAX_FRACTION_DIGITS);
54     }
55
56     private final byte scaleOffset;
57     private final long value;
58
59     @VisibleForTesting
60     Decimal64(final int fractionDigits, final long intPart, final long fracPart, final boolean negative) {
61         checkArgument(fractionDigits >= 1 && fractionDigits <= MAX_FRACTION_DIGITS);
62         this.scaleOffset = (byte) (fractionDigits - 1);
63
64         final long bits = intPart * SCALE[this.scaleOffset] + fracPart;
65         this.value = negative ? -bits : bits;
66     }
67
68     public static Decimal64 valueOf(final byte byteVal) {
69         return byteVal < 0 ? new Decimal64(1, -byteVal, 0, true) : new Decimal64(1, byteVal, 0, false);
70     }
71
72     public static Decimal64 valueOf(final short shortVal) {
73         return shortVal < 0 ? new Decimal64(1, -shortVal, 0, true) : new Decimal64(1, shortVal, 0, false);
74     }
75
76     public static Decimal64 valueOf(final int intVal) {
77         return intVal < 0 ? new Decimal64(1, - (long)intVal, 0, true) : new Decimal64(1, intVal, 0, false);
78     }
79
80     public static Decimal64 valueOf(final long longVal) {
81         // XXX: we should be able to do something smarter here
82         return valueOf(Long.toString(longVal));
83     }
84
85     public static Decimal64 valueOf(final double doubleVal) {
86         // XXX: we should be able to do something smarter here
87         return valueOf(Double.toString(doubleVal));
88     }
89
90     public static Decimal64 valueOf(final BigDecimal decimalVal) {
91         // XXX: we should be able to do something smarter here
92         return valueOf(decimalVal.toPlainString());
93     }
94
95     /**
96      * Attempt to parse a String into a Decimal64. This method uses minimum fraction digits required to hold
97      * the entire value.
98      *
99      * @param str String to parser
100      * @return A Decimal64 instance
101      * @throws NullPointerException if value is null.
102      * @throws NumberFormatException if the string does not contain a parsable decimal64.
103      */
104     public static Decimal64 valueOf(final String str) {
105         // https://tools.ietf.org/html/rfc6020#section-9.3.1
106         //
107         // A decimal64 value is lexically represented as an optional sign ("+"
108         // or "-"), followed by a sequence of decimal digits, optionally
109         // followed by a period ('.') as a decimal indicator and a sequence of
110         // decimal digits.  If no sign is specified, "+" is assumed.
111         if (str.isEmpty()) {
112             throw new NumberFormatException("Empty string is not a valid decimal64 representation");
113         }
114
115         // Deal with optional sign
116         final boolean negative;
117         int idx;
118         switch (str.charAt(0)) {
119             case '-':
120                 negative = true;
121                 idx = 1;
122                 break;
123             case '+':
124                 negative = false;
125                 idx = 1;
126                 break;
127             default:
128                 negative = false;
129                 idx = 0;
130         }
131
132         // Sanity check length
133         if (idx == str.length()) {
134             throw new NumberFormatException("Missing digits after sign");
135         }
136
137         // Character limit, used for caching and cutting trailing zeroes
138         int limit = str.length() - 1;
139
140         // Skip any leading zeroes, but leave at least one
141         for (; idx < limit && str.charAt(idx) == '0'; idx++) {
142             final char ch = str.charAt(idx + 1);
143             if (ch < '0' || ch > '9') {
144                 break;
145             }
146         }
147
148         // Integer part and its length
149         int intLen = 0;
150         long intPart = 0;
151
152         for (; idx <= limit; idx++, intLen++) {
153             final char ch = str.charAt(idx);
154             if (ch == '.') {
155                 // Fractions are next
156                 break;
157             }
158             if (intLen == MAX_FRACTION_DIGITS) {
159                 throw new NumberFormatException("Integer part is longer than " + MAX_FRACTION_DIGITS + " digits");
160             }
161
162             intPart = 10 * intPart + toInt(ch, idx);
163         }
164
165         if (idx > limit) {
166             // No fraction digits, we are done
167             return new Decimal64((byte)1, intPart, 0, negative);
168         }
169
170         // Bump index to skip over period and check the remainder
171         idx++;
172         if (idx > limit) {
173             throw new NumberFormatException("Value '" + str + "' is missing fraction digits");
174         }
175
176         // Trim trailing zeroes, if any
177         while (idx < limit && str.charAt(limit) == '0') {
178             limit--;
179         }
180
181         final int fracLimit = MAX_FRACTION_DIGITS - intLen;
182         byte fracLen = 0;
183         long fracPart = 0;
184         for (; idx <= limit; idx++, fracLen++) {
185             final char ch = str.charAt(idx);
186             if (fracLen == fracLimit) {
187                 throw new NumberFormatException("Fraction part longer than " + fracLimit + " digits");
188             }
189
190             fracPart = 10 * fracPart + toInt(ch, idx);
191         }
192
193         return new Decimal64(fracLen, intPart, fracPart, negative);
194     }
195
196     public BigDecimal decimalValue() {
197         return BigDecimal.valueOf(value, scaleOffset + 1);
198     }
199
200     @Override
201     public int intValue() {
202         return (int) intPart();
203     }
204
205     @Override
206     public long longValue() {
207         return intPart();
208     }
209
210     @Override
211     public float floatValue() {
212         return (float) doubleValue();
213     }
214
215     @Override
216     public double doubleValue() {
217         return 1.0 * value / SCALE[scaleOffset];
218     }
219
220     /**
221      * Converts this {@code BigDecimal} to a {@code byte}, checking for lost information. If this {@code Decimal64} has
222      * a nonzero fractional part or is out of the possible range for a {@code byte} result then
223      * an {@code ArithmeticException} is thrown.
224      *
225      * @return this {@code Decimal64} converted to a {@code byte}.
226      * @throws ArithmeticException if {@code this} has a nonzero fractional part, or will not fit in a {@code byte}.
227      */
228     public byte byteValueExact() {
229         final long val = longValueExact();
230         final byte ret = (byte) val;
231         if (val != ret) {
232             throw new ArithmeticException("Value " + val + " is outside of byte range");
233         }
234         return ret;
235     }
236
237     /**
238      * Converts this {@code BigDecimal} to a {@code short}, checking for lost information. If this {@code Decimal64} has
239      * a nonzero fractional part or is out of the possible range for a {@code short} result then
240      * an {@code ArithmeticException} is thrown.
241      *
242      * @return this {@code Decimal64} converted to a {@code short}.
243      * @throws ArithmeticException if {@code this} has a nonzero fractional part, or will not fit in a {@code short}.
244      */
245     public short shortValueExact() {
246         final long val = longValueExact();
247         final short ret = (short) val;
248         if (val != ret) {
249             throw new ArithmeticException("Value " + val + " is outside of short range");
250         }
251         return ret;
252     }
253
254     /**
255      * Converts this {@code BigDecimal} to an {@code int}, checking for lost information. If this {@code Decimal64} has
256      * a nonzero fractional part or is out of the possible range for an {@code int} result then
257      * an {@code ArithmeticException} is thrown.
258      *
259      * @return this {@code Decimal64} converted to an {@code int}.
260      * @throws ArithmeticException if {@code this} has a nonzero fractional part, or will not fit in an {@code int}.
261      */
262     public int intValueExact() {
263         final long val = longValueExact();
264         final int ret = (int) val;
265         if (val != ret) {
266             throw new ArithmeticException("Value " + val + " is outside of integer range");
267         }
268         return ret;
269     }
270
271     /**
272      * Converts this {@code BigDecimal} to a {@code long}, checking for lost information.  If this {@code Decimal64} has
273      * a nonzero fractional part then an {@code ArithmeticException} is thrown.
274      *
275      * @return this {@code Decimal64} converted to a {@code long}.
276      * @throws ArithmeticException if {@code this} has a nonzero fractional part.
277      */
278     public long longValueExact() {
279         if (fracPart() != 0) {
280             throw new ArithmeticException("Conversion of " + this + " would lose fraction");
281         }
282         return intPart();
283     }
284
285     @Override
286     @SuppressWarnings("checkstyle:parameterName")
287     public int compareTo(final Decimal64 o) {
288         if (this == o) {
289             return 0;
290         }
291         if (scaleOffset == o.scaleOffset) {
292             return Long.compare(value, o.value);
293         }
294
295         // XXX: we could do something smarter here
296         return Double.compare(doubleValue(), o.doubleValue());
297     }
298
299     @Override
300     public int hashCode() {
301         // We need to normalize the results in order to be consistent with equals()
302         return Long.hashCode(intPart()) * 31 + Long.hashCode(fracPart());
303     }
304
305     @Override
306     public boolean equals(final Object obj) {
307         if (this == obj) {
308             return true;
309         }
310         if (!(obj instanceof Decimal64)) {
311             return false;
312         }
313         final Decimal64 other = (Decimal64) obj;
314         if (scaleOffset == other.scaleOffset) {
315             return value == other.value;
316         }
317
318         // We need to normalize both
319         return intPart() == other.intPart() && fracPart() == fracPart();
320     }
321
322     @Override
323     public String toString() {
324         // https://tools.ietf.org/html/rfc6020#section-9.3.2
325         //
326         // The canonical form of a positive decimal64 does not include the sign
327         // "+".  The decimal point is required.  Leading and trailing zeros are
328         // prohibited, subject to the rule that there MUST be at least one digit
329         // before and after the decimal point.  The value zero is represented as
330         // "0.0".
331         final StringBuilder sb = new StringBuilder(21).append(intPart()).append('.');
332         final long fracPart = fracPart();
333         if (fracPart != 0) {
334             // We may need to zero-pad the fraction part
335             sb.append(Strings.padStart(Long.toString(fracPart), scaleOffset + 1, '0'));
336         } else {
337             sb.append('0');
338         }
339
340         return sb.toString();
341     }
342
343     private long intPart() {
344         return value / SCALE[scaleOffset];
345     }
346
347     private long fracPart() {
348         return Math.abs(value % SCALE[scaleOffset]);
349     }
350
351     private static int toInt(final char ch, final int index) {
352         if (ch < '0' || ch > '9') {
353             throw new NumberFormatException("Illegal character at offset " + index);
354         }
355         return ch - '0';
356     }
357 }