Debian Codegraph @

net/sf/saxon/value/BigDecimalValue.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.value;
9
10 import net.sf.saxon.om.SequenceTool;
11 import net.sf.saxon.trans.Err;
12 import net.sf.saxon.trans.XPathException;
13 import net.sf.saxon.tree.util.FastStringBuffer;
14 import net.sf.saxon.type.*;
15
16 import java.math.BigDecimal;
17 import java.math.BigInteger;
18 import java.math.RoundingMode;
19 import java.util.regex.Pattern;
20
21 /**
22 * An implementation class for decimal values other than integers
23 * @since 9.8. This class was previously named "DecimalValue". In 9.8 a new DecimalValue
24 * class is introduced, to more faithfully reflect the XDM type hierarchy, so that every
25 * instance of xs:decimal is now implemented as an instance of DecimalValue.
26 */
27
28 public final class BigDecimalValue extends DecimalValue {
29
30 public static final int DIVIDE_PRECISION = 18;
31
32 private BigDecimal value;
33 private Double doubleValue;
34
35 public static final BigDecimal BIG_DECIMAL_ONE_MILLION = BigDecimal.valueOf(1_000_000);
36 public static final BigDecimal BIG_DECIMAL_ONE_BILLION = BigDecimal.valueOf(1_000_000_000);
37
38 public static final BigDecimalValue ZERO = new BigDecimalValue(BigDecimal.valueOf(0));
39 public static final BigDecimalValue ONE = new BigDecimalValue(BigDecimal.valueOf(1));
40 public static final BigDecimalValue TWO = new BigDecimalValue(BigDecimal.valueOf(2));
41 public static final BigDecimalValue THREE = new BigDecimalValue(BigDecimal.valueOf(3));
42 public static final BigDecimal MAX_INT = BigDecimal.valueOf(Integer.MAX_VALUE);
43
44 /**
45 * Constructor supplying a BigDecimal
46 *
47 * @param value the value of the DecimalValue
48 */
49
50 public BigDecimalValue(BigDecimal value) {
51 this.value = value.stripTrailingZeros();
52 typeLabel = BuiltInAtomicType.DECIMAL;
53 }
54
55 private static final Pattern decimalPattern = Pattern.compile("(\\-|\\+)?((\\.[0-9]+)|([0-9]+(\\.[0-9]*)?))");
56
57 /**
58 * Factory method to construct a DecimalValue from a string
59 *
60 * @param in the value of the DecimalValue
61 * @param validate true if validation is required; false if the caller knows that the value is valid
62 * @return the required DecimalValue if the input is valid, or a ValidationFailure encapsulating the error
63 * message if not.
64 */
65
66 public static ConversionResult makeDecimalValue(CharSequence in, boolean validate) {
67
68 try {
69 return parse(in);
70 } catch (NumberFormatException err) {
71 ValidationFailure e = new ValidationFailure(
72 "Cannot convert string " + Err.wrap(Whitespace.trim(in), Err.VALUE) +
73 " to xs:decimal: " + err.getMessage());
74 e.setErrorCode("FORG0001");
75 return e;
76 }
77 }
78
79 /**
80 * Factory method to construct a DecimalValue from a string, throwing an unchecked exception
81 * if the value is invalid
82 *
83 * @param in the lexical representation of the DecimalValue
84 * @return the required DecimalValue
85 * @throws NumberFormatException if the value is invalid
86 */
87
88 public static BigDecimalValue parse(CharSequence in) throws NumberFormatException {
89 FastStringBuffer digits = new FastStringBuffer(in.length());
90 int scale = 0;
91 int state = 0;
92 // 0 - in initial whitespace; 1 - after sign
93 // 3 - after decimal point; 5 - in final whitespace
94 boolean foundDigit = false;
95 int len = in.length();
96 for (int i = 0; i < len; i++) {
97 char c = in.charAt(i);
98 switch (c) {
99 case ' ':
100 case '\t':
101 case '\r':
102 case '\n':
103 if (state != 0) {
104 state = 5;
105 }
106 break;
107 case '+':
108 if (state != 0) {
109 throw new NumberFormatException("unexpected sign");
110 }
111 state = 1;
112 break;
113 case '-':
114 if (state != 0) {
115 throw new NumberFormatException("unexpected sign");
116 }
117 state = 1;
118 digits.append(c);
119 break;
120 case '0':
121 case '1':
122 case '2':
123 case '3':
124 case '4':
125 case '5':
126 case '6':
127 case '7':
128 case '8':
129 case '9':
130 if (state == 0) {
131 state = 1;
132 } else if (state >= 3) {
133 scale++;
134 }
135 if (state == 5) {
136 throw new NumberFormatException("contains embedded whitespace");
137 }
138 digits.append(c);
139 foundDigit = true;
140 break;
141 case '.':
142 if (state == 5) {
143 throw new NumberFormatException("contains embedded whitespace");
144 }
145 if (state >= 3) {
146 throw new NumberFormatException("more than one decimal point");
147 }
148 state = 3;
149 break;
150 default:
151 throw new NumberFormatException("invalid character '" + c + "'");
152 }
153
154 }
155
156 if (!foundDigit) {
157 throw new NumberFormatException("no digits in value");
158 }
159
160 // remove insignificant trailing zeroes
161 while (scale > 0) {
162 if (digits.charAt(digits.length() - 1) == '0') {
163 digits.setLength(digits.length() - 1);
164 scale--;
165 } else {
166 break;
167 }
168 }
169 if (digits.isEmpty() || (digits.length() == 1 && digits.charAt(0) == '-')) {
170 return BigDecimalValue.ZERO;
171 }
172 BigInteger bigInt = new BigInteger(digits.toString());
173 BigDecimal bigDec = new BigDecimal(bigInt, scale);
174 return new BigDecimalValue(bigDec);
175 }
176
177 /**
178 * Test whether a string is castable to a decimal value
179 *
180 * @param in the string to be tested
181 * @return true if the string has the correct format for a decimal
182 */
183
184 public static boolean castableAsDecimal(CharSequence in) {
185 CharSequence trimmed = Whitespace.trimWhitespace(in);
186 return decimalPattern.matcher(trimmed).matches();
187 }
188
189 /**
190 * Constructor supplying a double
191 *
192 * @param in the value of the DecimalValue
193 * @throws ValidationException if the supplied value cannot be converted, typically because it is INF or NaN.
194 */
195
196 public BigDecimalValue(double in) throws ValidationException {
197 try {
198 BigDecimal d = new BigDecimal(in);
199 value = d.stripTrailingZeros();
200 } catch (NumberFormatException err) {
201 // Must be a special value such as NaN or infinity
202 ValidationFailure e = new ValidationFailure(
203 "Cannot convert double " + Err.wrap(in + "", Err.VALUE) + " to decimal");
204 e.setErrorCode("FOCA0002");
205 throw e.makeException();
206 }
207 typeLabel = BuiltInAtomicType.DECIMAL;
208 }
209
210 /**
211 * Constructor supplying a long integer
212 *
213 * @param in the value of the DecimalValue
214 */
215
216 public BigDecimalValue(long in) {
217 value = BigDecimal.valueOf(in);
218 typeLabel = BuiltInAtomicType.DECIMAL;
219 }
220
221 /**
222 * Create a copy of this atomic value, with a different type label
223 *
224 * @param typeLabel the type label of the new copy. The caller is responsible for checking that
225 * the value actually conforms to this type.
226 */
227
228 public AtomicValue copyAsSubType(AtomicType typeLabel) {
229 BigDecimalValue v = new BigDecimalValue(value);
230 v.typeLabel = typeLabel;
231 return v;
232 }
233
234 /**
235 * Determine the primitive type of the value. This delivers the same answer as
236 * getItemType().getPrimitiveItemType(). The primitive types are
237 * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration,
238 * and xs:untypedAtomic. For external objects, the result is AnyAtomicType.
239 */
240
241 public BuiltInAtomicType getPrimitiveType() {
242 return BuiltInAtomicType.DECIMAL;
243 }
244
245 /**
246 * Get the numeric value as a double
247 *
248 * @return A double representing this numeric value; NaN if it cannot be
249 * converted
250 */
251 @Override
252 public double getDoubleValue() {
253 if (doubleValue == null) {
254 double d = value.doubleValue();
255 doubleValue = d;
256 return d;
257 } else {
258 return doubleValue;
259 }
260 }
261
262 /**
263 * Get the numeric value converted to a float
264 *
265 * @return a float representing this numeric value; NaN if it cannot be converted
266 */
267 @Override
268 public float getFloatValue() {
269 return (float) value.doubleValue();
270 }
271
272 /**
273 * Return the numeric value as a Java long.
274 *
275 * @return the numeric value as a Java long. This performs truncation
276 * towards zero.
277 * @throws net.sf.saxon.trans.XPathException
278 * if the value cannot be converted
279 */
280 @Override
281 public long longValue() throws XPathException {
282 return (long) value.doubleValue();
283 }
284
285 /**
286 * Get the value
287 */
288
289 public BigDecimal getDecimalValue() {
290 return value;
291 }
292
293 /**
294 * Get the hashCode. This must conform to the rules for other NumericValue hashcodes
295 *
296 * @see NumericValue#hashCode
297 */
298
299 public int hashCode() {
300 BigDecimal round = value.setScale(0, RoundingMode.DOWN);
301 long value = round.longValue();
302 if (value > Integer.MIN_VALUE && value < Integer.MAX_VALUE) {
303 return (int) value;
304 } else {
305 return Double.valueOf(getDoubleValue()).hashCode();
306 }
307 }
308
309 public boolean effectiveBooleanValue() {
310 return value.signum() != 0;
311 }
312
313 /**
314 * Get the value of the item as a CharSequence. This is in some cases more efficient than
315 * the version of the method that returns a String.
316 */
317
318 // public CharSequence getStringValueCS() {
319 // return decimalToString(value, new FastStringBuffer(20));
320 // }
321
322 /**
323 * Get the canonical lexical representation as defined in XML Schema. This is not always the same
324 * as the result of casting to a string according to the XPath rules. For xs:decimal, the canonical
325 * representation always contains a decimal point.
326 */
327
328 public CharSequence getCanonicalLexicalRepresentation() {
329 String s = getStringValue();
330 if (s.indexOf('.') < 0) {
331 s += ".0";
332 }
333 return s;
334 }
335
336 /**
337 * Get the value as a String
338 *
339 * @return a String representation of the value
340 */
341
342 /*@NotNull*/
343 public CharSequence getPrimitiveStringValue() {
344 return decimalToString(value, new FastStringBuffer(FastStringBuffer.C16));
345 }
346
347 /**
348 * Convert a decimal value to a string, using the XPath rules for formatting
349 *
350 * @param value the decimal value to be converted
351 * @param fsb the FastStringBuffer to which the value is to be appended
352 * @return the supplied FastStringBuffer, suitably populated
353 */
354
355 public static FastStringBuffer decimalToString(BigDecimal value, FastStringBuffer fsb) {
356 // Can't use BigDecimal#toString() under JDK 1.5 because this produces values like "1E-5".
357 // Can't use BigDecimal#toPlainString() because it retains trailing zeroes to represent the scale
358 int scale = value.scale();
359 if (scale == 0) {
360 fsb.append(value.toString());
361 return fsb;
362 } else if (scale < 0) {
363 String s = value.abs().unscaledValue().toString();
364 if (s.equals("0")) {
365 fsb.append('0');
366 return fsb;
367 }
368 //FastStringBuffer sb = new FastStringBuffer(s.length() + (-scale) + 2);
369 if (value.signum() < 0) {
370 fsb.append('-');
371 }
372 fsb.append(s);
373 for (int i = 0; i < -scale; i++) {
374 fsb.append('0');
375 }
376 return fsb;
377 } else {
378 String s = value.abs().unscaledValue().toString();
379 if (s.equals("0")) {
380 fsb.append('0');
381 return fsb;
382 }
383 int len = s.length();
384 //FastStringBuffer sb = new FastStringBuffer(len+1);
385 if (value.signum() < 0) {
386 fsb.append('-');
387 }
388 if (scale >= len) {
389 fsb.append("0.");
390 for (int i = len; i < scale; i++) {
391 fsb.append('0');
392 }
393 fsb.append(s);
394 } else {
395 fsb.append(s.substring(0, len - scale));
396 fsb.append('.');
397 fsb.append(s.substring(len - scale));
398 }
399 return fsb;
400 }
401 }
402
403 /**
404 * Negate the value
405 */
406
407 public NumericValue negate() {
408 return new BigDecimalValue(value.negate());
409 }
410
411 /**
412 * Implement the XPath floor() function
413 */
414
415 public NumericValue floor() {
416 return new BigDecimalValue(value.setScale(0, RoundingMode.FLOOR));
417 }
418
419 /**
420 * Implement the XPath ceiling() function
421 */
422
423 public NumericValue ceiling() {
424 return new BigDecimalValue(value.setScale(0, RoundingMode.CEILING));
425 }
426
427 /**
428 * Implement the XPath round() function
429 */
430
431 public NumericValue round(int scale) {
432 // The XPath rules say that we should round to the nearest integer, with .5 rounding towards
433 // positive infinity. Unfortunately this is not one of the rounding modes that the Java BigDecimal
434 // class supports, so we need different rules depending on the value.
435
436 // If the value is positive, we use ROUND_HALF_UP; if it is negative, we use ROUND_HALF_DOWN (here "UP"
437 // means "away from zero")
438
439 if (scale >= value.scale()) {
440 // no-op - see bug #4027
441 return this;
442 }
443
444 switch (value.signum()) {
445 case -1:
446 return new BigDecimalValue(value.setScale(scale, RoundingMode.HALF_DOWN));
447 case 0:
448 return this;
449 case +1:
450 return new BigDecimalValue(value.setScale(scale, RoundingMode.HALF_UP));
451 default:
452 // can't happen
453 return this;
454 }
455
456 }
457
458 /**
459 * Implement the XPath round-half-to-even() function
460 */
461
462 public NumericValue roundHalfToEven(int scale) {
463 if (scale >= value.scale()) {
464 return this;
465 }
466 BigDecimal scaledValue = value.setScale(scale, RoundingMode.HALF_EVEN);
467 return new BigDecimalValue(scaledValue.stripTrailingZeros());
468 }
469
470 /**
471 * Determine whether the value is negative, zero, or positive
472 *
473 * @return -1 if negative, 0 if zero, +1 if positive, NaN if NaN
474 */
475
476 public int signum() {
477 return value.signum();
478 }
479
480 /**
481 * Determine whether the value is a whole number, that is, whether it compares
482 * equal to some integer
483 */
484
485 public boolean isWholeNumber() {
486 return value.scale() == 0 ||
487 value.compareTo(value.setScale(0, RoundingMode.DOWN)) == 0;
488 }
489
490 /**
491 * Test whether a number is a possible subscript into a sequence, that is,
492 * a whole number greater than zero and less than 2^31
493 *
494 * @return the number as an int if it is a possible subscript, or -1 otherwise
495 */
496 @Override
497 public int asSubscript() {
498 if (isWholeNumber() && value.compareTo(BigDecimal.ZERO) > 0 && value.compareTo(MAX_INT) <= 0) {
499 try {
500 return (int)longValue();
501 } catch (XPathException e) {
502 return -1;
503 }
504 } else {
505 return -1;
506 }
507 }
508
509 /**
510 * Get the absolute value as defined by the XPath abs() function
511 *
512 * @return the absolute value
513 * @since 9.2
514 */
515
516 public NumericValue abs() {
517 if (value.signum() > 0) {
518 return this;
519 } else {
520 return new BigDecimalValue(value.negate());
521 }
522 }
523
524 /**
525 * Compare the value to another numeric value
526 */
527
528 public int compareTo(NumericValue other) {
529 if (NumericValue.isInteger((NumericValue) other)) {
530 // deliberately triggers a ClassCastException if other value is the wrong type
531 try {
532 return value.compareTo(((NumericValue) other).getDecimalValue());
533 } catch (XPathException err) {
534 throw new AssertionError("Conversion of integer to decimal should never fail");
535 }
536 } else if (other instanceof BigDecimalValue) {
537 return value.compareTo(((BigDecimalValue) other).value);
538 } else if (other instanceof FloatValue) {
539 return 0 - ((FloatValue) other).compareTo(this);
540 } else {
541 return super.compareTo(other);
542 }
543 }
544
545 /**
546 * Compare the value to a long
547 *
548 * @param other the value to be compared with
549 * @return -1 if this is less, 0 if this is equal, +1 if this is greater or if this is NaN
550 */
551
552 public int compareTo(long other) {
553 if (other == 0) {
554 return value.signum();
555 }
556 return value.compareTo(BigDecimal.valueOf(other));
557 }
558
559 /**
560 * Get a Comparable value that implements the XML Schema ordering comparison semantics for this value.
561 * Returns null if the value is not comparable according to XML Schema rules. The default implementation
562 * returns the value itself if it is comparable, or null otherwise. This is modified for types such as
563 * xs:duration which allow ordering comparisons in XML Schema, but not in XPath.
564 * <p>In the case of data types that are partially ordered, the returned Comparable extends the standard
565 * semantics of the compareTo() method by returning the value {@link net.sf.saxon.om.SequenceTool#INDETERMINATE_ORDERING} when there
566 * is no defined order relationship between two given values.</p>
567 */
568
569 /**
570 * Get an object that implements XML Schema comparison semantics
571 */
572
573 public Comparable getSchemaComparable() {
574 return new DecimalComparable(this);
575 }
576
577 /**
578 * A Comparable that performs comparison of a DecimalValue either with another
579 * DecimalValue or with some other representation of an XPath numeric value
580 */
581
582 protected static class DecimalComparable implements Comparable {
583
584 protected BigDecimalValue value;
585
586 public DecimalComparable(BigDecimalValue value) {
587 this.value = value;
588 }
589
590 public BigDecimal asBigDecimal() {
591 return value.getDecimalValue();
592 }
593
594 public int compareTo(Object o) {
595 if (o instanceof DecimalComparable) {
596 return asBigDecimal().compareTo(((DecimalComparable) o).asBigDecimal());
597 } else if (o instanceof Int64Value.Int64Comparable) {
598 return asBigDecimal().compareTo(BigDecimal.valueOf(((Int64Value.Int64Comparable) o).asLong()));
599 } else if (o instanceof BigIntegerValue.BigIntegerComparable) {
600 return asBigDecimal().compareTo(new BigDecimal(((BigIntegerValue.BigIntegerComparable) o).asBigInteger()));
601 } else {
602 return SequenceTool.INDETERMINATE_ORDERING;
603 }
604 }
605
606 public boolean equals(Object o) {
607 return compareTo(o) == 0;
608 }
609
610 public int hashCode() {
611 // Must align with hashCodes for other subtypes of xs:decimal
612 if (value.isWholeNumber()) {
613 IntegerValue iv = Converter.DecimalToInteger.INSTANCE.convert(value);
614 return iv.getSchemaComparable().hashCode();
615
616 }
617 return value.hashCode();
618 }
619 }
620
621 /**
622 * Determine whether two atomic values are identical, as determined by XML Schema rules. This is a stronger
623 * test than equality (even schema-equality); for example two dateTime values are not identical unless
624 * they are in the same timezone.
625 * <p>Note that even this check ignores the type annotation of the value. The integer 3 and the short 3
626 * are considered identical, even though they are not fully interchangeable. "Identical" means the
627 * same point in the value space, regardless of type annotation.</p>
628 * <p>NaN is identical to itself.</p>
629 *
630 * @param v the other value to be compared with this one
631 * @return true if the two values are identical, false otherwise.
632 */
633
634 public boolean isIdentical(/*@NotNull*/ AtomicValue v) {
635 return (v instanceof DecimalValue) && equals(v);
636 }
637
638 }
639