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.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
21 * Dedicated type for YANG's 'type decimal64' type. This class is similar to {@link BigDecimal}, but provides more
22 * efficient storage, as it has fixed precision.
24 * @author Robert Varga
28 public class Decimal64 extends Number implements CanonicalValue<Decimal64> {
29 private static final class Support extends AbstractCanonicalValueSupport<Decimal64> {
31 super(Decimal64.class);
35 public Decimal64 fromString(final String str) {
36 return Decimal64.valueOf(str);
40 private static final CanonicalValueSupport<Decimal64> SUPPORT = new Support();
41 private static final long serialVersionUID = 1L;
43 private static final int MAX_FRACTION_DIGITS = 18;
45 private static final long[] SCALE = {
67 verify(SCALE.length == MAX_FRACTION_DIGITS);
70 private final byte scaleOffset;
71 private final long value;
74 Decimal64(final int fractionDigits, final long intPart, final long fracPart, final boolean negative) {
75 checkArgument(fractionDigits >= 1 && fractionDigits <= MAX_FRACTION_DIGITS);
76 this.scaleOffset = (byte) (fractionDigits - 1);
78 final long bits = intPart * SCALE[this.scaleOffset] + fracPart;
79 this.value = negative ? -bits : bits;
82 protected Decimal64(final Decimal64 other) {
83 this.scaleOffset = other.scaleOffset;
84 this.value = other.value;
87 public static Decimal64 valueOf(final byte byteVal) {
88 return byteVal < 0 ? new Decimal64(1, -byteVal, 0, true) : new Decimal64(1, byteVal, 0, false);
91 public static Decimal64 valueOf(final short shortVal) {
92 return shortVal < 0 ? new Decimal64(1, -shortVal, 0, true) : new Decimal64(1, shortVal, 0, false);
95 public static Decimal64 valueOf(final int intVal) {
96 return intVal < 0 ? new Decimal64(1, - (long)intVal, 0, true) : new Decimal64(1, intVal, 0, false);
99 public static Decimal64 valueOf(final long longVal) {
100 // XXX: we should be able to do something smarter here
101 return valueOf(Long.toString(longVal));
104 public static Decimal64 valueOf(final double doubleVal) {
105 // XXX: we should be able to do something smarter here
106 return valueOf(Double.toString(doubleVal));
109 public static Decimal64 valueOf(final BigDecimal decimalVal) {
110 // XXX: we should be able to do something smarter here
111 return valueOf(decimalVal.toPlainString());
115 * Attempt to parse a String into a Decimal64. This method uses minimum fraction digits required to hold
118 * @param str String to parser
119 * @return A Decimal64 instance
120 * @throws NullPointerException if value is null.
121 * @throws NumberFormatException if the string does not contain a parsable decimal64.
123 public static Decimal64 valueOf(final String str) {
124 // https://tools.ietf.org/html/rfc6020#section-9.3.1
126 // A decimal64 value is lexically represented as an optional sign ("+"
127 // or "-"), followed by a sequence of decimal digits, optionally
128 // followed by a period ('.') as a decimal indicator and a sequence of
129 // decimal digits. If no sign is specified, "+" is assumed.
131 throw new NumberFormatException("Empty string is not a valid decimal64 representation");
134 // Deal with optional sign
135 final boolean negative;
137 switch (str.charAt(0)) {
151 // Sanity check length
152 if (idx == str.length()) {
153 throw new NumberFormatException("Missing digits after sign");
156 // Character limit, used for caching and cutting trailing zeroes
157 int limit = str.length() - 1;
159 // Skip any leading zeroes, but leave at least one
160 for (; idx < limit && str.charAt(idx) == '0'; idx++) {
161 final char ch = str.charAt(idx + 1);
162 if (ch < '0' || ch > '9') {
167 // Integer part and its length
171 for (; idx <= limit; idx++, intLen++) {
172 final char ch = str.charAt(idx);
174 // Fractions are next
177 if (intLen == MAX_FRACTION_DIGITS) {
178 throw new NumberFormatException("Integer part is longer than " + MAX_FRACTION_DIGITS + " digits");
181 intPart = 10 * intPart + toInt(ch, idx);
185 // No fraction digits, we are done
186 return new Decimal64((byte)1, intPart, 0, negative);
189 // Bump index to skip over period and check the remainder
192 throw new NumberFormatException("Value '" + str + "' is missing fraction digits");
195 // Trim trailing zeroes, if any
196 while (idx < limit && str.charAt(limit) == '0') {
200 final int fracLimit = MAX_FRACTION_DIGITS - intLen;
203 for (; idx <= limit; idx++, fracLen++) {
204 final char ch = str.charAt(idx);
205 if (fracLen == fracLimit) {
206 throw new NumberFormatException("Fraction part longer than " + fracLimit + " digits");
209 fracPart = 10 * fracPart + toInt(ch, idx);
212 return new Decimal64(fracLen, intPart, fracPart, negative);
215 public final BigDecimal decimalValue() {
216 return BigDecimal.valueOf(value, scaleOffset + 1);
220 public final int intValue() {
221 return (int) intPart();
225 public final long longValue() {
230 public final float floatValue() {
231 return (float) doubleValue();
235 public final double doubleValue() {
236 return 1.0 * value / SCALE[scaleOffset];
240 * Converts this {@code BigDecimal} to a {@code byte}, checking for lost information. If this {@code Decimal64} has
241 * a nonzero fractional part or is out of the possible range for a {@code byte} result then
242 * an {@code ArithmeticException} is thrown.
244 * @return this {@code Decimal64} converted to a {@code byte}.
245 * @throws ArithmeticException if {@code this} has a nonzero fractional part, or will not fit in a {@code byte}.
247 public final byte byteValueExact() {
248 final long val = longValueExact();
249 final byte ret = (byte) val;
251 throw new ArithmeticException("Value " + val + " is outside of byte range");
257 * Converts this {@code BigDecimal} to a {@code short}, checking for lost information. If this {@code Decimal64} has
258 * a nonzero fractional part or is out of the possible range for a {@code short} result then
259 * an {@code ArithmeticException} is thrown.
261 * @return this {@code Decimal64} converted to a {@code short}.
262 * @throws ArithmeticException if {@code this} has a nonzero fractional part, or will not fit in a {@code short}.
264 public final short shortValueExact() {
265 final long val = longValueExact();
266 final short ret = (short) val;
268 throw new ArithmeticException("Value " + val + " is outside of short range");
274 * Converts this {@code BigDecimal} to an {@code int}, checking for lost information. If this {@code Decimal64} has
275 * a nonzero fractional part or is out of the possible range for an {@code int} result then
276 * an {@code ArithmeticException} is thrown.
278 * @return this {@code Decimal64} converted to an {@code int}.
279 * @throws ArithmeticException if {@code this} has a nonzero fractional part, or will not fit in an {@code int}.
281 public final int intValueExact() {
282 final long val = longValueExact();
283 final int ret = (int) val;
285 throw new ArithmeticException("Value " + val + " is outside of integer range");
291 * Converts this {@code BigDecimal} to a {@code long}, checking for lost information. If this {@code Decimal64} has
292 * a nonzero fractional part then an {@code ArithmeticException} is thrown.
294 * @return this {@code Decimal64} converted to a {@code long}.
295 * @throws ArithmeticException if {@code this} has a nonzero fractional part.
297 public final long longValueExact() {
298 if (fracPart() != 0) {
299 throw new ArithmeticException("Conversion of " + this + " would lose fraction");
305 @SuppressWarnings("checkstyle:parameterName")
306 public final int compareTo(final Decimal64 o) {
310 if (scaleOffset == o.scaleOffset) {
311 return Long.compare(value, o.value);
314 // XXX: we could do something smarter here
315 return Double.compare(doubleValue(), o.doubleValue());
319 public final String toCanonicalString() {
320 // https://tools.ietf.org/html/rfc6020#section-9.3.2
322 // The canonical form of a positive decimal64 does not include the sign
323 // "+". The decimal point is required. Leading and trailing zeros are
324 // prohibited, subject to the rule that there MUST be at least one digit
325 // before and after the decimal point. The value zero is represented as
327 final StringBuilder sb = new StringBuilder(21).append(intPart()).append('.');
328 final long fracPart = fracPart();
330 // We may need to zero-pad the fraction part
331 sb.append(Strings.padStart(Long.toString(fracPart), scaleOffset + 1, '0'));
336 return sb.toString();
340 public final CanonicalValueSupport<Decimal64> support() {
345 public final int hashCode() {
346 // We need to normalize the results in order to be consistent with equals()
347 return Long.hashCode(intPart()) * 31 + Long.hashCode(fracPart());
351 public final boolean equals(final @Nullable Object obj) {
355 if (!(obj instanceof Decimal64)) {
358 final Decimal64 other = (Decimal64) obj;
359 if (scaleOffset == other.scaleOffset) {
360 return value == other.value;
363 // We need to normalize both
364 return intPart() == other.intPart() && fracPart() == fracPart();
368 public final String toString() {
369 return toCanonicalString();
372 private long intPart() {
373 return value / SCALE[scaleOffset];
376 private long fracPart() {
377 return Math.abs(value % SCALE[scaleOffset]);
380 private static int toInt(final char ch, final int index) {
381 if (ch < '0' || ch > '9') {
382 throw new NumberFormatException("Illegal character at offset " + index);