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.model.util.type;
10 import com.google.common.base.Function;
11 import com.google.common.collect.ImmutableMap;
12 import java.math.BigDecimal;
13 import java.math.BigInteger;
16 final class NumberUtil {
17 private static final Map<Class<? extends Number>, Function<Number, Number>> CONVERTERS;
19 final ImmutableMap.Builder<Class<? extends Number>, Function<Number, Number>> b = ImmutableMap.builder();
20 b.put(Byte.class, new Function<Number, Number>() {
22 public Number apply(final Number input) {
23 if (input instanceof Byte) {
27 return Byte.valueOf(input.toString());
30 b.put(Short.class, new Function<Number, Number>() {
32 public Number apply(final Number input) {
33 if (input instanceof Short) {
36 if (input instanceof Byte) {
37 return input.shortValue();
40 return Short.valueOf(input.toString());
43 b.put(Integer.class, new Function<Number, Number>() {
45 public Number apply(final Number input) {
46 if (input instanceof Integer) {
49 if (input instanceof Byte || input instanceof Short) {
50 return input.intValue();
53 return Integer.valueOf(input.toString());
56 b.put(Long.class, new Function<Number, Number>() {
58 public Number apply(final Number input) {
59 if (input instanceof Long) {
62 if (input instanceof Byte || input instanceof Short || input instanceof Integer) {
63 return input.longValue();
66 return Long.valueOf(input.toString());
69 b.put(BigDecimal.class, new Function<Number, Number>() {
71 public Number apply(final Number input) {
72 if (input instanceof BigDecimal) {
75 if (input instanceof Byte || input instanceof Short ||
76 input instanceof Integer || input instanceof Long) {
77 return BigDecimal.valueOf(input.longValue());
80 return new BigDecimal(input.toString());
83 b.put(BigInteger.class, new Function<Number, Number>() {
85 public Number apply(final Number input) {
86 if (input instanceof BigInteger) {
89 if (input instanceof Byte || input instanceof Short ||
90 input instanceof Integer || input instanceof Long) {
91 return BigInteger.valueOf(input.longValue());
94 return new BigInteger(input.toString());
97 CONVERTERS = b.build();
100 private NumberUtil() {
101 throw new UnsupportedOperationException();
104 static Function<Number, Number> converterTo(final Class<? extends Number> clazz) {
105 return CONVERTERS.get(clazz);