001/* 002 * Copyright 2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.revetsec.json; 018 019import com.revetsec.internal.json.JsonWriter; 020import org.jspecify.annotations.NonNull; 021import org.jspecify.annotations.Nullable; 022 023import javax.annotation.concurrent.Immutable; 024import java.math.BigDecimal; 025import java.util.Optional; 026 027import static java.util.Objects.requireNonNull; 028 029/** 030 * A JSON number, held exactly as a {@link BigDecimal}. There is no floating-point form. 031 * <p> 032 * <strong>Caps.</strong> A number has at most 4,096 significant digits (its {@link BigDecimal#precision()}) and an 033 * adjusted decimal exponent (precision − scale − 1, the exponent of its leading digit) of magnitude at 034 * most 100,000, so it always renders in bounded space and compares in bounded time. 035 * <p> 036 * <strong>Equality</strong> is by numeric value: {@code 1}, {@code 1.0}, {@code 1E0} and {@code 0.1E1} are equal and 037 * have the same hash code, which is computed once from the nearest {@code double}. No method expands a number to its 038 * plain form, so {@code 1E+100000} costs no more to compare or hash than {@code 1}. 039 * <p> 040 * <strong>Rendering.</strong> {@link #toJson()} writes the canonical form of {@link BigDecimal#toString()}, not the 041 * text a number was parsed from: {@code 1e2} becomes {@code 1E+2}, {@code -0} becomes {@code 0}, and {@code 1.50} 042 * stays {@code 1.50}. 043 * 044 * @author <a href="https://www.revetkn.com">Mark Allen</a> 045 * @since 1.0.0 046 */ 047@Immutable 048public final class JsonNumber implements JsonValue { 049 /** 050 * A long has at most 19 digits, so only an adjusted exponent from 0 to 18 can hold a non-zero whole long. 051 */ 052 private static final long MAXIMUM_LONG_ADJUSTED_EXPONENT = 18; 053 054 @NonNull 055 private final BigDecimal value; 056 private final int hashCode; 057 058 /** 059 * Returns a JSON number holding {@code value} exactly. 060 * <p> 061 * A subclass of {@link BigDecimal} is first copied into a {@code BigDecimal} with the same unscaled value and 062 * scale, and the copy is what the number checks, holds and renders, so the number can never change later. 063 * 064 * @param value the number's value 065 * @return the JSON number 066 * @throws NullPointerException if {@code value} is {@code null} 067 * @throws IllegalArgumentException if {@code value} has more than 4,096 digits, or an adjusted exponent of 068 * magnitude above 100,000 069 * @since 1.0.0 070 */ 071 @NonNull 072 public static JsonNumber fromValue(@NonNull BigDecimal value) { 073 return new JsonNumber(JsonInvariants.requireNumberWithinCaps(JsonInvariants.exactBigDecimal(value))); 074 } 075 076 /** 077 * Returns a JSON number holding {@code value}. 078 * 079 * @param value the number's value 080 * @return the JSON number 081 * @throws NullPointerException if {@code value} is {@code null} 082 * @since 1.0.0 083 */ 084 @NonNull 085 public static JsonNumber fromValue(@NonNull Long value) { 086 requireNonNull(value); 087 return new JsonNumber(BigDecimal.valueOf(value.longValue())); 088 } 089 090 private JsonNumber(@NonNull BigDecimal value) { 091 this.value = value; 092 // Numerically equal values have the same exact value, so the same correctly rounded double. 093 this.hashCode = Double.hashCode(value.doubleValue()); 094 } 095 096 /** 097 * Returns this number's exact value, with the scale it was given or parsed with. It is always an instance of 098 * {@link BigDecimal} itself, never a subclass. 099 * 100 * @return the value 101 * @since 1.0.0 102 */ 103 @NonNull 104 public BigDecimal getValue() { 105 return this.value; 106 } 107 108 /** 109 * Returns this number as a {@code long}, if it is a whole number in the range of {@code long}. Trailing zeros after 110 * the decimal point do not matter: {@code 42.0} and {@code 4.2E+1} give 42. 111 * 112 * @return the value, or empty if it has a non-zero fraction or is outside the range of {@code long} 113 * @since 1.0.0 114 */ 115 @NonNull 116 public Optional<@NonNull Long> getLongValueExact() { 117 if (this.value.signum() == 0) 118 return Optional.of(0L); 119 120 long adjustedExponent = JsonInvariants.adjustedExponent(this.value); 121 122 // Rejects magnitudes below 1 or above 10^19 before any rescaling, so the cost never depends on the exponent. 123 if (adjustedExponent < 0 || adjustedExponent > MAXIMUM_LONG_ADJUSTED_EXPONENT) 124 return Optional.empty(); 125 126 try { 127 return Optional.of(this.value.longValueExact()); 128 } catch (ArithmeticException exception) { 129 return Optional.empty(); 130 } 131 } 132 133 @Override 134 @NonNull 135 public String toJson() { 136 return JsonWriter.toJson(this); 137 } 138 139 @Override 140 public boolean equals(@Nullable Object other) { 141 return this == other || (other instanceof JsonNumber number && this.hashCode == number.hashCode 142 && this.value.compareTo(number.value) == 0); 143 } 144 145 @Override 146 public int hashCode() { 147 return this.hashCode; 148 } 149 150 @Override 151 @NonNull 152 public String toString() { 153 return "JsonNumber{value=<redacted>}"; 154 } 155}