-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathJavaBigDecimalFromCharArray.java
More file actions
326 lines (301 loc) · 13.7 KB
/
JavaBigDecimalFromCharArray.java
File metadata and controls
326 lines (301 loc) · 13.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/*
* @(#)JavaBigDecimalFromCharArray.java
* Copyright © 2023 Werner Randelshofer, Switzerland. MIT License.
*/
package ch.randelshofer.fastdoubleparser;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import java.util.NavigableMap;
import static ch.randelshofer.fastdoubleparser.FastIntegerMath.*;
import static ch.randelshofer.fastdoubleparser.ParseDigitsTaskCharArray.RECURSION_THRESHOLD;
/**
* Parses a {@code double} from a {@code byte} array.
*/
final class JavaBigDecimalFromCharArray extends AbstractBigDecimalParser {
/**
* Creates a new instance.
*/
public JavaBigDecimalFromCharArray() {
}
/**
* Parses a {@code BigDecimalString} as specified in {@link JavaBigDecimalParser}.
*
* @param str the input string
* @param offset start of the input data
* @param length length of the input data
* @return the parsed {@link BigDecimal}
* @throws NullPointerException if str is null
* @throws IllegalArgumentException if offset or length are illegal
* @throws NumberFormatException if the input string can not be parsed successfully
*/
public BigDecimal parseBigDecimalString(char[] str, int offset, int length) {
try {
final int endIndex = checkBounds(str.length, offset, length);
if (hasManyDigits(length)) {
return parseBigDecimalStringWithManyDigits(str, offset, length);
}
long significand = 0L;
final int integerPartIndex;
int decimalPointIndex = -1;
final int exponentIndicatorIndex;
int index = offset;
char ch = charAt(str, index, endIndex);
boolean illegal = false;
// Parse optional sign
// -------------------
final boolean isNegative = ch == '-';
if (isNegative || ch == '+') {
ch = charAt(str, ++index, endIndex);
if (ch == 0) {
throw new NumberFormatException(SYNTAX_ERROR);
}
}
// Parse significand
integerPartIndex = index;
for (; index < endIndex; index++) {
ch = str[index];
if (FastDoubleSwar.isDigit(ch)) {
// This might overflow, we deal with it later.
significand = 10 * (significand) + ch - '0';
} else if (ch == '.') {
illegal |= decimalPointIndex >= 0;
decimalPointIndex = index;
for (; index < endIndex - 4; index += 4) {
int digits = FastDoubleSwar.tryToParseFourDigits(str, index + 1);
if (digits < 0) {
break;
}
// This might overflow, we deal with it later.
significand = 10_000L * significand + digits;
}
} else {
break;
}
}
final int digitCount;
final int significandEndIndex = index;
long exponent;
if (decimalPointIndex < 0) {
digitCount = significandEndIndex - integerPartIndex;
decimalPointIndex = significandEndIndex;
exponent = 0;
} else {
digitCount = significandEndIndex - integerPartIndex - 1;
exponent = decimalPointIndex - significandEndIndex + 1;
}
// Parse exponent number
// ---------------------
long expNumber = 0;
if ((ch | 0x20) == 'e') {// equals ignore case
exponentIndicatorIndex = index;
ch = charAt(str, ++index, endIndex);
boolean isExponentNegative = ch == '-';
if (isExponentNegative || ch == '+') {
ch = charAt(str, ++index, endIndex);
}
illegal |= !FastDoubleSwar.isDigit(ch);
do {
// Guard against overflow
if (expNumber < MAX_EXPONENT_NUMBER) {
expNumber = 10 * (expNumber) + ch - '0';
}
ch = charAt(str, ++index, endIndex);
} while (FastDoubleSwar.isDigit(ch));
if (isExponentNegative) {
expNumber = -expNumber;
}
exponent += expNumber;
} else {
exponentIndicatorIndex = endIndex;
}
illegal |= digitCount == 0;
checkParsedBigDecimalBounds(illegal, index, endIndex, digitCount, exponent);
if (digitCount < 19) {
return new BigDecimal(isNegative ? -significand : significand).scaleByPowerOfTen((int) exponent);
}
return valueOfBigDecimalString(str, integerPartIndex, decimalPointIndex, decimalPointIndex + 1, exponentIndicatorIndex, isNegative, (int) exponent);
} catch (ArithmeticException e) {
NumberFormatException nfe = new NumberFormatException(VALUE_EXCEEDS_LIMITS);
nfe.initCause(e);
throw nfe;
}
}
/**
* Parses a big decimal string that has many digits.
*/
BigDecimal parseBigDecimalStringWithManyDigits(char[] str, int offset, int length) {
final int nonZeroIntegerPartIndex;
final int integerPartIndex;
int nonZeroFractionalPartIndex = -1;
int decimalPointIndex = -1;
final int exponentIndicatorIndex;
final int endIndex = offset + length;
int index = offset;
char ch = charAt(str, index, endIndex);
boolean illegal = false;
// Parse optional sign
// -------------------
final boolean isNegative = ch == '-';
if (isNegative || ch == '+') {
ch = charAt(str, ++index, endIndex);
if (ch == 0) {
throw new NumberFormatException(SYNTAX_ERROR);
}
}
// Count digits of significand
// -----------------
integerPartIndex = index;
int swarLimit = Math.min(endIndex - 8, 1 << 30);
while (index < swarLimit && FastDoubleSwar.isEightZeroes(str, index)) {
index += 8;
}
while (index < endIndex && str[index] == '0') {
index++;
}
// Count digits of integer part
nonZeroIntegerPartIndex = index;
while (index < swarLimit && FastDoubleSwar.isEightDigits(str, index)) {
index += 8;
}
while (index < endIndex && FastDoubleSwar.isDigit(ch = str[index])) {
index++;
}
if (ch == '.') {
decimalPointIndex = index++;
// skip leading zeroes
while (index < swarLimit && FastDoubleSwar.isEightZeroes(str, index)) {
index += 8;
}
while (index < endIndex && str[index] == '0') {
index++;
}
nonZeroFractionalPartIndex = index;
// Count digits of fraction part
while (index < swarLimit && FastDoubleSwar.isEightDigits(str, index)) {
index += 8;
}
while (index < endIndex && FastDoubleSwar.isDigit(ch = str[index])) {
index++;
}
}
final int digitCountWithoutLeadingZeros;
final int significandEndIndex = index;
long exponent;
if (decimalPointIndex < 0) {
digitCountWithoutLeadingZeros = significandEndIndex - nonZeroIntegerPartIndex;
decimalPointIndex = significandEndIndex;
nonZeroFractionalPartIndex = significandEndIndex;
exponent = 0;
} else {
digitCountWithoutLeadingZeros = nonZeroIntegerPartIndex == decimalPointIndex
? significandEndIndex - nonZeroFractionalPartIndex
: significandEndIndex - nonZeroIntegerPartIndex - 1;
exponent = decimalPointIndex - significandEndIndex + 1;
}
// Parse exponent number
// ---------------------
long expNumber = 0;
if ((ch | 0x20) == 'e') {// equals ignore case
exponentIndicatorIndex = index;
ch = charAt(str, ++index, endIndex);
boolean isExponentNegative = ch == '-';
if (isExponentNegative || ch == '+') {
ch = charAt(str, ++index, endIndex);
}
illegal = !FastDoubleSwar.isDigit(ch);
do {
// Guard against overflow
if (expNumber < MAX_EXPONENT_NUMBER) {
expNumber = 10 * (expNumber) + ch - '0';
}
ch = charAt(str, ++index, endIndex);
} while (FastDoubleSwar.isDigit(ch));
if (isExponentNegative) {
expNumber = -expNumber;
}
exponent += expNumber;
} else {
exponentIndicatorIndex = endIndex;
}
illegal |= integerPartIndex == decimalPointIndex && decimalPointIndex == exponentIndicatorIndex;
checkParsedBigDecimalBounds(illegal, index, endIndex, digitCountWithoutLeadingZeros, exponent);
return valueOfBigDecimalString(str, nonZeroIntegerPartIndex, decimalPointIndex, nonZeroFractionalPartIndex, exponentIndicatorIndex, isNegative, (int) exponent);
}
/**
* Parses a big decimal string after we have identified the parts of the significand,
* and after we have obtained the exponent value.
* <pre>
* integerPartIndex
* │ decimalPointIndex
* │ │ nonZeroFractionalPartIndex
* │ │ │ exponentIndicatorIndex
* ↓ ↓ ↓ ↓
* "-123.00456e-789"
*
* </pre>
*
* @param str the input string
* @param integerPartIndex the start index of the integer part of the significand
* @param decimalPointIndex the index of the decimal point in the significand (same as exponentIndicatorIndex
* if there is no decimal point)
* @param nonZeroFractionalPartIndex the start index of the non-zero fractional part of the significand
* @param exponentIndicatorIndex the index of the exponent indicator (same as end of string if there is no
* exponent indicator)
* @param isNegative indicates that the significand is negative
* @param exponent the exponent value
* @return the parsed big decimal
*/
private BigDecimal valueOfBigDecimalString(char[] str, int integerPartIndex, int decimalPointIndex, int nonZeroFractionalPartIndex, int exponentIndicatorIndex, boolean isNegative, int exponent) {
int integerExponent = exponentIndicatorIndex - decimalPointIndex - 1;
int fractionDigitsCount = exponentIndicatorIndex - nonZeroFractionalPartIndex;
int integerDigitsCount = decimalPointIndex - integerPartIndex;
NavigableMap<Integer, BigInteger> powersOfTen = null;
Map<Integer, BigInteger> powersOfFive;
// Parse the significand
// ---------------------
BigInteger significand;
// If there is an integer part, we parse it using a recursive algorithm.
// The recursive algorithm needs a map with powers of ten, if we have more than RECURSION_THRESHOLD digits.
BigInteger integerPart;
if (integerDigitsCount > 0) {
if (integerDigitsCount > RECURSION_THRESHOLD) {
powersOfTen = createPowersOfTenFloor16Map();
fillPowersOfNFloor16Recursive(powersOfTen, integerPartIndex, decimalPointIndex);
powersOfFive = createPowersOfFive(powersOfTen);
integerPart = ParseDigitsTaskCharArray.parseDigitsRecursive(str, integerPartIndex, decimalPointIndex, powersOfTen, powersOfFive);
} else {
integerPart = ParseDigitsTaskCharArray.parseDigitsRecursive(str, integerPartIndex, decimalPointIndex, null, null);
}
} else {
integerPart = BigInteger.ZERO;
}
// If there is a fraction part, we parse it using a recursive algorithm.
// The recursive algorithm needs a map with powers of ten, if we have more than RECURSION_THRESHOLD digits.
if (fractionDigitsCount > 0) {
BigInteger fractionalPart;
if (fractionDigitsCount > RECURSION_THRESHOLD) {
if (powersOfTen == null) {
powersOfTen = createPowersOfTenFloor16Map();
}
fillPowersOfNFloor16Recursive(powersOfTen, decimalPointIndex + 1, exponentIndicatorIndex);
powersOfFive = createPowersOfFive(powersOfTen);
fractionalPart = ParseDigitsTaskCharArray.parseDigitsRecursive(str, decimalPointIndex + 1, exponentIndicatorIndex, powersOfTen, powersOfFive);
} else {
fractionalPart = ParseDigitsTaskCharArray.parseDigitsRecursive(str, decimalPointIndex + 1, exponentIndicatorIndex, null, null);
}
// If the integer part is not 0, we combine it with the fraction part.
if (integerPart.signum() == 0) {
significand = fractionalPart;
} else {
BigInteger integerFactor = computePowerOfTen(powersOfTen, integerExponent);
significand = FftMultiplier.multiply(integerPart, integerFactor).add(fractionalPart);
}
} else {
significand = integerPart;
}
// Combine the significand with the sign and the exponent
// ------------------------------------------------------
return new BigDecimal(isNegative ? significand.negate() : significand, -exponent);
}
}