2 * Copyright (c) 2015 Pantheon Technologies s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.common;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Verify.verify;
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;
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.
23 * @author Robert Varga
26 public final class Decimal64 extends Number implements Comparable<Decimal64>, Immutable {
27 private static final long serialVersionUID = 1L;
29 private static final int MAX_FRACTION_DIGITS = 18;
31 private static final long[] SCALE = {
53 verify(SCALE.length == MAX_FRACTION_DIGITS);
56 private final byte scaleOffset;
57 private final long value;
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);
64 final long bits = intPart * SCALE[this.scaleOffset] + fracPart;
65 this.value = negative ? -bits : bits;
68 public static Decimal64 valueOf(final byte byteVal) {
69 return byteVal < 0 ? new Decimal64(1, -byteVal, 0, true) : new Decimal64(1, byteVal, 0, false);
72 public static Decimal64 valueOf(final short shortVal) {
73 return shortVal < 0 ? new Decimal64(1, -shortVal, 0, true) : new Decimal64(1, shortVal, 0, false);
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);
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));
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));
90 public static Decimal64 valueOf(final BigDecimal decimalVal) {
91 // XXX: we should be able to do something smarter here
92 return valueOf(decimalVal.toPlainString());
96 * Attempt to parse a String into a Decimal64. This method uses minimum fraction digits required to hold
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.
104 public static Decimal64 valueOf(final String str) {
105 // https://tools.ietf.org/html/rfc6020#section-9.3.1
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.
112 throw new NumberFormatException("Empty string is not a valid decimal64 representation");
115 // Deal with optional sign
116 final boolean negative;
118 switch (str.charAt(0)) {
132 // Sanity check length
133 if (idx == str.length()) {
134 throw new NumberFormatException("Missing digits after sign");
137 // Character limit, used for caching and cutting trailing zeroes
138 int limit = str.length() - 1;
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') {
148 // Integer part and its length
152 for (; idx <= limit; idx++, intLen++) {
153 final char ch = str.charAt(idx);
155 // Fractions are next
158 if (intLen == MAX_FRACTION_DIGITS) {
159 throw new NumberFormatException("Integer part is longer than " + MAX_FRACTION_DIGITS + " digits");
162 intPart = 10 * intPart + toInt(ch, idx);
166 // No fraction digits, we are done
167 return new Decimal64((byte)1, intPart, 0, negative);
170 // Bump index to skip over period and check the remainder
173 throw new NumberFormatException("Value '" + str + "' is missing fraction digits");
176 // Trim trailing zeroes, if any
177 while (idx < limit && str.charAt(limit) == '0') {
181 final int fracLimit = MAX_FRACTION_DIGITS - intLen;
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");
190 fracPart = 10 * fracPart + toInt(ch, idx);
193 return new Decimal64(fracLen, intPart, fracPart, negative);
196 public BigDecimal decimalValue() {
197 return BigDecimal.valueOf(value, scaleOffset + 1);
201 public int intValue() {
202 return (int) intPart();
206 public long longValue() {
211 public float floatValue() {
212 return (float) doubleValue();
216 public double doubleValue() {
217 return 1.0 * value / SCALE[scaleOffset];
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.
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}.
228 public byte byteValueExact() {
229 final long val = longValueExact();
230 final byte ret = (byte) val;
232 throw new ArithmeticException("Value " + val + " is outside of byte range");
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.
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}.
245 public short shortValueExact() {
246 final long val = longValueExact();
247 final short ret = (short) val;
249 throw new ArithmeticException("Value " + val + " is outside of short range");
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.
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}.
262 public int intValueExact() {
263 final long val = longValueExact();
264 final int ret = (int) val;
266 throw new ArithmeticException("Value " + val + " is outside of integer range");
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.
275 * @return this {@code Decimal64} converted to a {@code long}.
276 * @throws ArithmeticException if {@code this} has a nonzero fractional part.
278 public long longValueExact() {
279 if (fracPart() != 0) {
280 throw new ArithmeticException("Conversion of " + this + " would lose fraction");
286 @SuppressWarnings("checkstyle:parameterName")
287 public int compareTo(final Decimal64 o) {
291 if (scaleOffset == o.scaleOffset) {
292 return Long.compare(value, o.value);
295 // XXX: we could do something smarter here
296 return Double.compare(doubleValue(), o.doubleValue());
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());
306 public boolean equals(final Object obj) {
310 if (!(obj instanceof Decimal64)) {
313 final Decimal64 other = (Decimal64) obj;
314 if (scaleOffset == other.scaleOffset) {
315 return value == other.value;
318 // We need to normalize both
319 return intPart() == other.intPart() && fracPart() == fracPart();
323 public String toString() {
324 // https://tools.ietf.org/html/rfc6020#section-9.3.2
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
331 final StringBuilder sb = new StringBuilder(21).append(intPart()).append('.');
332 final long fracPart = fracPart();
334 // We may need to zero-pad the fraction part
335 sb.append(Strings.padStart(Long.toString(fracPart), scaleOffset + 1, '0'));
340 return sb.toString();
343 private long intPart() {
344 return value / SCALE[scaleOffset];
347 private long fracPart() {
348 return Math.abs(value % SCALE[scaleOffset]);
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);