1   /*
2    * SPDX-FileCopyrightText: none
3    * SPDX-License-Identifier: CC0-1.0
4    */
5   
6   package dev.metaschema.core.metapath.item.atomic.impl;
7   
8   import java.math.BigDecimal;
9   import java.math.BigInteger;
10  import java.util.Objects;
11  
12  import dev.metaschema.core.datatype.adapter.DecimalAdapter;
13  import dev.metaschema.core.datatype.adapter.MetaschemaDataTypeProvider;
14  import dev.metaschema.core.metapath.item.atomic.IDecimalItem;
15  import edu.umd.cs.findbugs.annotations.NonNull;
16  
17  /**
18   * An implementation of a Metapath atomic item containing a decimal data value.
19   */
20  public class DecimalItemImpl
21      extends AbstractDecimalItem<BigDecimal> {
22    @NonNull
23    private static final BigDecimal BOOLEAN_TRUE = new BigDecimal("1.0");
24    @NonNull
25    private static final BigDecimal BOOLEAN_FALSE = new BigDecimal("0.0");
26  
27    /**
28     * Get the equivalent decimal value for the provided boolean value.
29     *
30     * @param value
31     *          the boolean value
32     * @return the equivalent decimal value
33     */
34    @NonNull
35    public static BigDecimal toBigDecimal(boolean value) {
36      return value ? BOOLEAN_TRUE : BOOLEAN_FALSE;
37    }
38  
39    /**
40     * Construct a new item with the provided {@code value}.
41     *
42     * @param value
43     *          the value to wrap
44     */
45    public DecimalItemImpl(@NonNull BigDecimal value) {
46      super(value);
47    }
48  
49    @Override
50    public DecimalAdapter getJavaTypeAdapter() {
51      return MetaschemaDataTypeProvider.DECIMAL;
52    }
53  
54    @Override
55    public BigDecimal asDecimal() {
56      return getValue();
57    }
58  
59    @SuppressWarnings("null")
60    @Override
61    public String asString() {
62      BigDecimal decimal = getValue();
63      // if the fractional part is empty, render as an integer
64      return decimal.scale() <= 0 ? decimal.toBigIntegerExact().toString() : decimal.toPlainString();
65    }
66  
67    @SuppressWarnings("null")
68    @Override
69    public BigInteger asInteger() {
70      return getValue().toBigInteger();
71    }
72  
73    @Override
74    public int hashCode() {
75      return Objects.hash(asDecimal());
76    }
77  
78    @Override
79    public boolean equals(Object obj) {
80      return this == obj
81          || obj instanceof IDecimalItem && compareTo((IDecimalItem) obj) == 0;
82    }
83  }