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 java.util.Optional;
18 import org.eclipse.jdt.annotation.NonNullByDefault;
19 import org.eclipse.jdt.annotation.Nullable;
20 import org.opendaylight.yangtools.concepts.Either;
23 * Dedicated type for YANG's 'type decimal64' type. This class is similar to {@link BigDecimal}, but provides more
24 * efficient storage, as it has fixed precision.
26 * @author Robert Varga
30 public class Decimal64 extends Number implements CanonicalValue<Decimal64> {
31 public static final class Support extends AbstractCanonicalValueSupport<Decimal64> {
33 super(Decimal64.class);
37 public Either<Decimal64, CanonicalValueViolation> fromString(final String str) {
38 // https://tools.ietf.org/html/rfc6020#section-9.3.1
40 // A decimal64 value is lexically represented as an optional sign ("+"
41 // or "-"), followed by a sequence of decimal digits, optionally
42 // followed by a period ('.') as a decimal indicator and a sequence of
43 // decimal digits. If no sign is specified, "+" is assumed.
45 return CanonicalValueViolation.variantOf("Empty string is not a valid decimal64 representation");
48 // Deal with optional sign
49 final boolean negative;
51 switch (str.charAt(0)) {
65 // Sanity check length
66 if (idx == str.length()) {
67 return CanonicalValueViolation.variantOf("Missing digits after sign");
70 // Character limit, used for caching and cutting trailing zeroes
71 int limit = str.length() - 1;
73 // Skip any leading zeroes, but leave at least one
74 for (; idx < limit && str.charAt(idx) == '0'; idx++) {
75 final char ch = str.charAt(idx + 1);
76 if (ch < '0' || ch > '9') {
81 // Integer part and its length
85 for (; idx <= limit; idx++, intLen++) {
86 final char ch = str.charAt(idx);
91 if (intLen == MAX_SCALE) {
92 return CanonicalValueViolation.variantOf(
93 "Integer part is longer than " + MAX_SCALE + " digits");
96 intPart = 10 * intPart + toInt(ch, idx);
100 // No fraction digits, we are done
101 return Either.ofFirst(new Decimal64((byte)1, intPart, 0, negative));
104 // Bump index to skip over period and check the remainder
107 return CanonicalValueViolation.variantOf("Value '" + str + "' is missing fraction digits");
110 // Trim trailing zeroes, if any
111 while (idx < limit && str.charAt(limit) == '0') {
115 final int fracLimit = MAX_SCALE - intLen + 1;
118 for (; idx <= limit; idx++, fracLen++) {
119 final char ch = str.charAt(idx);
120 if (fracLen == fracLimit) {
121 return CanonicalValueViolation.variantOf("Fraction part longer than " + fracLimit + " digits");
124 fracPart = 10 * fracPart + toInt(ch, idx);
127 return Either.ofFirst(new Decimal64(fracLen, intPart, fracPart, negative));
130 private static int toInt(final char ch, final int index) {
131 if (ch < '0' || ch > '9') {
132 throw new NumberFormatException("Illegal character at offset " + index);
138 private static final CanonicalValueSupport<Decimal64> SUPPORT = new Support();
139 private static final long serialVersionUID = 1L;
141 private static final int MAX_SCALE = 18;
143 private static final long[] SCALE = {
165 verify(SCALE.length == MAX_SCALE);
168 private final byte scaleOffset;
169 private final long value;
172 Decimal64(final int scale, final long intPart, final long fracPart, final boolean negative) {
173 scaleOffset = offsetOf(scale);
175 final long bits = intPart * SCALE[scaleOffset] + fracPart;
176 value = negative ? -bits : bits;
179 private Decimal64(final byte scaleOffset, final long value) {
180 this.scaleOffset = scaleOffset;
184 protected Decimal64(final Decimal64 other) {
185 this(other.scaleOffset, other.value);
189 * Return a {@link Decimal64} with specified scale and unscaled value.
191 * @param scale scale to use
192 * @param unscaledValue unscaled value to use
193 * @return A Decimal64 instance
194 * @throws IllegalArgumentException if {@code scale} is not in range {@code [1..18]}
196 public static Decimal64 of(final int scale, final long unscaledValue) {
197 return new Decimal64(offsetOf(scale), unscaledValue);
200 // >>> FIXME: these need to take a scale value and perform a range check. we also need truncating counterparts
201 public static Decimal64 valueOf(final byte byteVal) {
202 return byteVal < 0 ? new Decimal64(1, -byteVal, 0, true) : new Decimal64(1, byteVal, 0, false);
205 public static Decimal64 valueOf(final short shortVal) {
206 return shortVal < 0 ? new Decimal64(1, -shortVal, 0, true) : new Decimal64(1, shortVal, 0, false);
209 public static Decimal64 valueOf(final int intVal) {
210 return intVal < 0 ? new Decimal64(1, - (long)intVal, 0, true) : new Decimal64(1, intVal, 0, false);
213 public static Decimal64 valueOf(final long longVal) {
214 // XXX: we should be able to do something smarter here
215 return valueOf(Long.toString(longVal));
219 // FIXME: this should take a RoundingMode and perform rounding
220 // FIXME: this should have a float counterpart
221 // FIXME: this should have a truncating
222 public static Decimal64 valueOf(final double doubleVal) {
223 // XXX: we should be able to do something smarter here
224 return valueOf(Double.toString(doubleVal));
227 public static Decimal64 valueOf(final BigDecimal decimalVal) {
228 // FIXME: we should be able to do something smarter here using BigDecimal.unscaledValue() and BigDecimal.scale()
229 return valueOf(decimalVal.toPlainString());
233 * Attempt to parse a String into a Decimal64. This method uses minimum fraction digits required to hold
236 * @param str String to parser
237 * @return A Decimal64 instance
238 * @throws NullPointerException if value is null.
239 * @throws NumberFormatException if the string does not contain a parsable decimal64.
241 public static Decimal64 valueOf(final String str) {
242 final Either<Decimal64, CanonicalValueViolation> variant = SUPPORT.fromString(str);
243 final Optional<Decimal64> value = variant.tryFirst();
244 if (value.isPresent()) {
247 final Optional<String> message = variant.getSecond().getMessage();
248 throw message.isPresent() ? new NumberFormatException(message.get()) : new NumberFormatException();
252 * Return the scale of this decimal. This is the number of fraction digits, in range {@code [1..18]}.
254 * @return This decimal's scale
256 public final int scale() {
257 return scaleOffset + 1;
261 * Return the unscaled value of this decimal.
263 * @return This decimal's unscaled value
265 public final long unscaledValue() {
269 public final BigDecimal decimalValue() {
270 return BigDecimal.valueOf(value, scale());
274 public final int intValue() {
275 return (int) intPart();
279 public final long longValue() {
284 public final float floatValue() {
285 return (float) doubleValue();
289 public final double doubleValue() {
290 return 1.0 * value / SCALE[scaleOffset];
294 * Converts this {@code BigDecimal} to a {@code byte}, checking for lost information. If this {@code Decimal64} has
295 * a nonzero fractional part or is out of the possible range for a {@code byte} result then
296 * an {@code ArithmeticException} is thrown.
298 * @return this {@code Decimal64} converted to a {@code byte}.
299 * @throws ArithmeticException if {@code this} has a nonzero fractional part, or will not fit in a {@code byte}.
301 public final byte byteValueExact() {
302 final long val = longValueExact();
303 final byte ret = (byte) val;
305 throw new ArithmeticException("Value " + val + " is outside of byte range");
311 * Converts this {@code BigDecimal} to a {@code short}, checking for lost information. If this {@code Decimal64} has
312 * a nonzero fractional part or is out of the possible range for a {@code short} result then
313 * an {@code ArithmeticException} is thrown.
315 * @return this {@code Decimal64} converted to a {@code short}.
316 * @throws ArithmeticException if {@code this} has a nonzero fractional part, or will not fit in a {@code short}.
318 public final short shortValueExact() {
319 final long val = longValueExact();
320 final short ret = (short) val;
322 throw new ArithmeticException("Value " + val + " is outside of short range");
328 * Converts this {@code BigDecimal} to an {@code int}, checking for lost information. If this {@code Decimal64} has
329 * a nonzero fractional part or is out of the possible range for an {@code int} result then
330 * an {@code ArithmeticException} is thrown.
332 * @return this {@code Decimal64} converted to an {@code int}.
333 * @throws ArithmeticException if {@code this} has a nonzero fractional part, or will not fit in an {@code int}.
335 public final int intValueExact() {
336 final long val = longValueExact();
337 final int ret = (int) val;
339 throw new ArithmeticException("Value " + val + " is outside of integer range");
345 * Converts this {@code BigDecimal} to a {@code long}, checking for lost information. If this {@code Decimal64} has
346 * a nonzero fractional part then an {@code ArithmeticException} is thrown.
348 * @return this {@code Decimal64} converted to a {@code long}.
349 * @throws ArithmeticException if {@code this} has a nonzero fractional part.
351 public final long longValueExact() {
352 if (fracPart() != 0) {
353 throw new ArithmeticException("Conversion of " + this + " would lose fraction");
359 @SuppressWarnings("checkstyle:parameterName")
360 public final int compareTo(final Decimal64 o) {
364 if (scaleOffset == o.scaleOffset) {
365 return Long.compare(value, o.value);
368 // XXX: we could do something smarter here
369 return Double.compare(doubleValue(), o.doubleValue());
373 public final String toCanonicalString() {
374 // https://tools.ietf.org/html/rfc6020#section-9.3.2
376 // The canonical form of a positive decimal64 does not include the sign
377 // "+". The decimal point is required. Leading and trailing zeros are
378 // prohibited, subject to the rule that there MUST be at least one digit
379 // before and after the decimal point. The value zero is represented as
381 final StringBuilder sb = new StringBuilder(21).append(intPart()).append('.');
382 final long fracPart = fracPart();
384 // We may need to zero-pad the fraction part
385 sb.append(Strings.padStart(Long.toString(fracPart), scale(), '0'));
390 return sb.toString();
394 public final CanonicalValueSupport<Decimal64> support() {
399 public final int hashCode() {
400 // We need to normalize the results in order to be consistent with equals()
401 return Long.hashCode(intPart()) * 31 + Long.hashCode(fracPart());
405 public final boolean equals(final @Nullable Object obj) {
406 return this == obj || obj instanceof Decimal64 && equalsImpl((Decimal64) obj);
410 * A slightly faster version of {@link #equals(Object)}.
412 * @param obj Decimal64 object
413 * @return {@code true} if this object is the same as the obj argument; {@code false} otherwise.
415 public final boolean equals(final @Nullable Decimal64 obj) {
416 return this == obj || obj != null && equalsImpl(obj);
420 public final String toString() {
421 return toCanonicalString();
424 private boolean equalsImpl(final Decimal64 other) {
425 return scaleOffset == other.scaleOffset ? value == other.value
426 // We need to normalize both
427 : intPart() == other.intPart() && fracPart() == other.fracPart();
430 private long intPart() {
431 return value / SCALE[scaleOffset];
434 private long fracPart() {
435 return Math.abs(value % SCALE[scaleOffset]);
438 private static byte offsetOf(final int scale) {
439 checkArgument(scale >= 1 && scale <= MAX_SCALE);
440 return (byte) (scale - 1);