Debian Codegraph @

net/sf/saxon/value/BigIntegerValue.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.expr.Calculator;
11 import net.sf.saxon.om.SequenceTool;
12 import net.sf.saxon.om.StandardNames;
13 import net.sf.saxon.trans.XPathException;
14 import net.sf.saxon.type.AtomicType;
15 import net.sf.saxon.type.BuiltInAtomicType;
16 import net.sf.saxon.type.ConversionResult;
17 import net.sf.saxon.type.ValidationFailure;
18
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
21
22 /**
23 * An integer value: note this is a subtype of decimal in XML Schema, not a primitive type.
24 * The abstract class IntegerValue is used to represent any xs:integer value; this implementation
25 * is used for values that do not fit comfortably in a Java long; including the built-in subtype xs:unsignedLong
26 */
27
28 public final class BigIntegerValue extends IntegerValue {
29
30 private BigInteger value;
31
32 private static final BigInteger MAX_INT = BigInteger.valueOf(Integer.MAX_VALUE);
33 private static final BigInteger MIN_INT = BigInteger.valueOf(Integer.MIN_VALUE);
34 public static final BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);
35 public static final BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE);
36 /*@NotNull*/ public static final BigInteger MAX_UNSIGNED_LONG = new BigInteger("18446744073709551615");
37 /*@NotNull*/ public static final BigIntegerValue ZERO = new BigIntegerValue(BigInteger.ZERO);
38
39 /**
40 * Construct an xs:integer value from a Java BigInteger
41 *
42 * @param value the supplied BigInteger
43 */
44
45 public BigIntegerValue(BigInteger value) {
46 this.value = value;
47 typeLabel = BuiltInAtomicType.INTEGER;
48 }
49
50 /**
51 * Construct an xs:integer value from a Java BigInteger, supplying a type label.
52 * It is the caller's responsibility to ensure that the supplied value conforms
53 * with the rules for the specified type.
54 *
55 * @param value the value of the integer
56 * @param typeLabel the type, which must represent a type derived from xs:integer
57 */
58
59 public BigIntegerValue(BigInteger value, AtomicType typeLabel) {
60 this.value = value;
61 this.typeLabel = typeLabel;
62 }
63
64 /**
65 * Construct an xs:integer value from a Java long. Note: normally, if the value fits in a long,
66 * then an Int64Value should be used. This constructor is largely for internal use, when operations
67 * are required that require two integers to use the same implementation class to be used.
68 *
69 * @param value the supplied Java long
70 */
71
72 public BigIntegerValue(long value) {
73 this.value = BigInteger.valueOf(value);
74 typeLabel = BuiltInAtomicType.INTEGER;
75 }
76
77 /**
78 * Create a copy of this atomic value, with a different type label
79 *
80 * @param typeLabel the type label of the new copy. The caller is responsible for checking that
81 * the value actually conforms to this type.
82 */
83
84 /*@NotNull*/
85 public AtomicValue copyAsSubType(/*@NotNull*/ AtomicType typeLabel) {
86 if (typeLabel.getPrimitiveType() == StandardNames.XS_INTEGER) {
87 BigIntegerValue v = new BigIntegerValue(value);
88 v.typeLabel = typeLabel;
89 return v;
90 } else {
91 return new BigDecimalValue(new BigDecimal(value));
92 }
93
94 }
95
96 /**
97 * This class allows subtypes of xs:integer to be held, as well as xs:integer values.
98 * This method sets the required type label. Note that this method modifies the value in situ.
99 *
100 * @param type the subtype of integer required
101 * @return null if the operation succeeds, or a ValidationException if the value is out of range
102 */
103
104 /*@Nullable*/
105 public ValidationFailure convertToSubType(/*@NotNull*/ BuiltInAtomicType type, boolean validate) {
106 if (!validate) {
107 typeLabel = type;
108 return null;
109 }
110 if (IntegerValue.checkBigRange(value, type)) {
111 typeLabel = type;
112 return null;
113 } else {
114 ValidationFailure err = new ValidationFailure(
115 "Integer value is out of range for subtype " + type.getDisplayName());
116 err.setErrorCode("FORG0001");
117 return err;
118 }
119 }
120
121
122 /**
123 * This class allows subtypes of xs:integer to be held, as well as xs:integer values.
124 * This method checks that the value is valid against the rules for a given subtype.
125 *
126 * @param type the subtype of integer required
127 * @return null if the operation succeeds, or a ValidationException if the value is out of range
128 */
129
130 /*@Nullable*/
131 public ValidationFailure validateAgainstSubType(/*@NotNull*/ BuiltInAtomicType type) {
132 if (IntegerValue.checkBigRange(value, type)) {
133 typeLabel = type;
134 return null;
135 } else {
136 ValidationFailure err = new ValidationFailure(
137 "Integer value is out of range for subtype " + type.getDisplayName());
138 err.setErrorCode("FORG0001");
139 return err;
140 }
141 }
142
143 /**
144 * Get the hashCode. This must conform to the rules for other NumericValue hashcodes
145 *
146 * @see NumericValue#hashCode
147 */
148
149 public int hashCode() {
150 if (value.compareTo(MIN_INT) >= 0 && value.compareTo(MAX_INT) <= 0) {
151 return value.intValue();
152 } else {
153 return Double.valueOf(getDoubleValue()).hashCode();
154 }
155 }
156
157 /**
158 * Get the value as a long
159 *
160 * @return the value of the xs:integer, as a Java long
161 */
162
163 public long longValue() {
164 return value.longValue();
165 }
166
167 /**
168 * Get the value as a BigInteger
169 *
170 * @return the value of the xs:integer as a Java BigInteger
171 */
172
173 public BigInteger asBigInteger() {
174 return value;
175 }
176
177 /**
178 * Test whether the value is within the range that can be held in a 64-bit signed integer
179 *
180 * @return true if the value is within range for a long
181 */
182
183 public boolean isWithinLongRange() {
184 return value.compareTo(MIN_LONG) >= 0 && value.compareTo(MAX_LONG) <= 0;
185 }
186
187 /**
188 * Convert the value to a BigDecimal
189 *
190 * @return the resulting BigDecimal
191 */
192
193 /*@NotNull*/
194 public BigDecimal asDecimal() {
195 return new BigDecimal(value);
196 }
197
198 /**
199 * Return the effective boolean value of this integer
200 *
201 * @return false if the integer is zero, otherwise true
202 */
203 public boolean effectiveBooleanValue() {
204 return value.compareTo(BigInteger.ZERO) != 0;
205 }
206
207 /**
208 * Compare the value to another numeric value
209 *
210 * @param other the numeric value to be compared to this value
211 * @return -1 if this value is less than the other, 0 if they are equal,
212 * +1 if this value is greater
213 */
214
215 public int compareTo(NumericValue other) {
216 if (other instanceof BigIntegerValue) {
217 return value.compareTo(((BigIntegerValue) other).value);
218 } else if (other instanceof Int64Value) {
219 return value.compareTo(BigInteger.valueOf(((Int64Value) other).longValue()));
220 } else if (other instanceof BigDecimalValue) {
221 return asDecimal().compareTo(((BigDecimalValue) other).getDecimalValue());
222 } else {
223 return super.compareTo(other);
224 }
225 }
226
227 /**
228 * Compare the value to a long
229 *
230 * @param other the value to be compared with
231 * @return -1 if this is less, 0 if this is equal, +1 if this is greater or if this is NaN
232 */
233
234 public int compareTo(long other) {
235 if (other == 0) {
236 return value.signum();
237 }
238 return value.compareTo(BigInteger.valueOf(other));
239 }
240
241
242 /**
243 * Get the value as a String
244 *
245 * @return a String representation of the value
246 */
247
248 public String getPrimitiveStringValue() {
249 return value.toString();
250 }
251
252 /**
253 * Get the numeric value as a double
254 *
255 * @return A double representing this numeric value; NaN if it cannot be
256 * converted
257 */
258 public double getDoubleValue() {
259 return value.doubleValue();
260 }
261
262 /**
263 * Get the numeric value converted to a decimal
264 *
265 * @return a decimal representing this numeric value;
266 */
267
268 /*@NotNull*/
269 public BigDecimal getDecimalValue() {
270 return new BigDecimal(value);
271 }
272
273 /**
274 * Get the numeric value converted to a float
275 *
276 * @return a float representing this numeric value; NaN if it cannot be converted
277 */
278 @Override
279 public float getFloatValue() {
280 return (float) getDoubleValue();
281 }
282
283 /**
284 * Negate the value
285 *
286 * @return the result of inverting the sign of the value
287 */
288
289 /*@NotNull*/
290 public NumericValue negate() {
291 return new BigIntegerValue(value.negate());
292 }
293
294 /**
295 * Implement the XPath floor() function
296 *
297 * @return the integer value, unchanged
298 */
299
300 /*@NotNull*/
301 public NumericValue floor() {
302 return this;
303 }
304
305 /**
306 * Implement the XPath ceiling() function
307 *
308 * @return the integer value, unchanged
309 */
310
311 /*@NotNull*/
312 public NumericValue ceiling() {
313 return this;
314 }
315
316 /**
317 * Implement the XPath round() function
318 *
319 * @return the integer value, unchanged
320 */
321
322 public NumericValue round(int scale) {
323 if (scale >= 0) {
324 return this;
325 } else {
326 BigInteger factor = BigInteger.valueOf(10).pow(-scale);
327 BigInteger[] pair = value.divideAndRemainder(factor);
328 int up = pair[1].compareTo(factor.divide(BigInteger.valueOf(2)));
329 if (up >= 0) {
330 // remainder is > .5
331 pair[0] = pair[0].add(BigInteger.valueOf(1));
332 }
333 return makeIntegerValue(pair[0].multiply(factor));
334 }
335 }
336
337 /**
338 * Implement the XPath round-to-half-even() function
339 *
340 * @param scale number of digits required after the decimal point; the
341 * value -2 (for example) means round to a multiple of 100
342 * @return if the scale is &gt;=0, return this value unchanged. Otherwise
343 * round it to a multiple of 10**-scale
344 */
345
346 public NumericValue roundHalfToEven(int scale) {
347 if (scale >= 0) {
348 return this;
349 } else {
350 BigInteger factor = BigInteger.valueOf(10).pow(-scale);
351 BigInteger[] pair = value.divideAndRemainder(factor);
352 int up = pair[1].compareTo(factor.divide(BigInteger.valueOf(2)));
353 if (up > 0) {
354 // remainder is > .5
355 pair[0] = pair[0].add(BigInteger.valueOf(1));
356 } else if (up == 0) {
357 // remainder == .5
358 if (pair[0].mod(BigInteger.valueOf(2)).signum() != 0) {
359 // last digit of quotient is odd: make it even
360 pair[0] = pair[0].add(BigInteger.valueOf(1));
361 }
362 }
363 return makeIntegerValue(pair[0].multiply(factor));
364 }
365 }
366
367 /**
368 * Determine whether the value is negative, zero, or positive
369 *
370 * @return -1 if negative, 0 if zero, +1 if positive, NaN if NaN
371 */
372
373 public int signum() {
374 return value.signum();
375 }
376
377 /**
378 * Get the absolute value as defined by the XPath abs() function
379 *
380 * @return the absolute value
381 */
382
383 /*@NotNull*/
384 public NumericValue abs() {
385 if (value.signum() >= 0) {
386 return this;
387 } else {
388 return new BigIntegerValue(value.abs());
389 }
390 }
391
392 /**
393 * Determine whether the value is a whole number, that is, whether it compares
394 * equal to some integer
395 *
396 * @return always true for this implementation
397 */
398
399 public boolean isWholeNumber() {
400 return true;
401 }
402
403 /**
404 * Test whether a number is a possible subscript into a sequence, that is,
405 * a whole number greater than zero and less than 2^31
406 *
407 * @return the number as an int if it is a possible subscript, or -1 otherwise
408 */
409 @Override
410 public int asSubscript() {
411 if (value.compareTo(BigInteger.ZERO) > 0 && value.compareTo(MAX_INT) <= 0) {
412 return (int)longValue();
413 } else {
414 return -1;
415 }
416 }
417
418 /**
419 * Add another integer
420 */
421
422 public IntegerValue plus(/*@NotNull*/ IntegerValue other) {
423 if (other instanceof BigIntegerValue) {
424 return makeIntegerValue(value.add(((BigIntegerValue) other).value));
425 } else {
426 //noinspection RedundantCast
427 return makeIntegerValue(value.add(BigInteger.valueOf(((Int64Value) other).longValue())));
428 }
429 }
430
431 /**
432 * Subtract another integer
433 */
434
435 public IntegerValue minus(/*@NotNull*/ IntegerValue other) {
436 if (other instanceof BigIntegerValue) {
437 return makeIntegerValue(value.subtract(((BigIntegerValue) other).value));
438 } else {
439 //noinspection RedundantCast
440 return makeIntegerValue(value.subtract(BigInteger.valueOf(((Int64Value) other).longValue())));
441 }
442 }
443
444 /**
445 * Multiply by another integer
446 */
447
448 public IntegerValue times(/*@NotNull*/ IntegerValue other) {
449 if (other instanceof BigIntegerValue) {
450 return makeIntegerValue(value.multiply(((BigIntegerValue) other).value));
451 } else {
452 //noinspection RedundantCast
453 return makeIntegerValue(value.multiply(BigInteger.valueOf(((Int64Value) other).longValue())));
454 }
455 }
456
457 /**
458 * Divide by another integer
459 *
460 * @throws net.sf.saxon.trans.XPathException
461 * if the other integer is zero
462 */
463
464 public NumericValue div(/*@NotNull*/ IntegerValue other) throws XPathException {
465 BigInteger oi;
466 if (other instanceof BigIntegerValue) {
467 oi = ((BigIntegerValue) other).value;
468 } else {
469 oi = BigInteger.valueOf(other.longValue());
470 }
471 BigDecimalValue a = new BigDecimalValue(new BigDecimal(value));
472 BigDecimalValue b = new BigDecimalValue(new BigDecimal(oi));
473 return Calculator.decimalDivide(a, b);
474 }
475
476 /**
477 * Take modulo another integer
478 *
479 * @throws net.sf.saxon.trans.XPathException
480 * if the other integer is zero
481 */
482
483 public IntegerValue mod(/*@NotNull*/ IntegerValue other) throws XPathException {
484 try {
485 if (other instanceof BigIntegerValue) {
486 return makeIntegerValue(value.remainder(((BigIntegerValue) other).value));
487 } else {
488 return makeIntegerValue(value.remainder(BigInteger.valueOf(other.longValue())));
489 }
490 } catch (ArithmeticException err) {
491 XPathException e;
492 if (BigInteger.valueOf(other.longValue()).signum() == 0) {
493 e = new XPathException("Integer modulo zero", "FOAR0001");
494 } else {
495 e = new XPathException("Integer mod operation failure", err);
496 }
497 throw e;
498 }
499 }
500
501 /**
502 * Integer divide by another integer
503 *
504 * @throws net.sf.saxon.trans.XPathException
505 * if the other integer is zero
506 */
507
508 public IntegerValue idiv(/*@NotNull*/ IntegerValue other) throws XPathException {
509 BigInteger oi;
510 if (other instanceof BigIntegerValue) {
511 oi = ((BigIntegerValue) other).value;
512 } else {
513 oi = BigInteger.valueOf(other.longValue());
514 }
515 try {
516 return makeIntegerValue(value.divide(oi));
517 } catch (ArithmeticException err) {
518 XPathException e;
519 if ("/ by zero".equals(err.getMessage())) {
520 e = new XPathException("Integer division by zero", "FOAR0001");
521 } else {
522 e = new XPathException("Integer division failure", err);
523 }
524 throw e;
525 }
526 }
527
528 /**
529 * Get an object that implements XML Schema comparison semantics
530 */
531
532 /*@NotNull*/
533 public Comparable getSchemaComparable() {
534 return new BigIntegerComparable(this);
535 }
536
537 /**
538 * A Comparable that performs comparison of BigInteger values either with other
539 * BigInteger values or with other representations of XPath numeric values
540 */
541
542 protected static class BigIntegerComparable implements Comparable {
543
544 protected BigIntegerValue value;
545
546 public BigIntegerComparable(BigIntegerValue value) {
547 this.value = value;
548 }
549
550 public BigInteger asBigInteger() {
551 return value.asBigInteger();
552 }
553
554 public int compareTo(/*@NotNull*/ Object o) {
555 if (o instanceof Int64Value.Int64Comparable) {
556 return asBigInteger().compareTo(BigInteger.valueOf(((Int64Value.Int64Comparable) o).asLong()));
557 } else if (o instanceof BigIntegerComparable) {
558 return asBigInteger().compareTo(((BigIntegerComparable) o).asBigInteger());
559 } else if (o instanceof BigDecimalValue.DecimalComparable) {
560 return value.getDecimalValue().compareTo(((BigDecimalValue.DecimalComparable) o).asBigDecimal());
561 } else {
562 return SequenceTool.INDETERMINATE_ORDERING;
563 }
564 }
565
566 public boolean equals(/*@NotNull*/ Object o) {
567 return compareTo(o) == 0;
568 }
569
570 public int hashCode() {
571 // Must align with hashCodes for other subtypes of xs:decimal
572 BigInteger big = value.asBigInteger();
573 if (big.compareTo(MAX_LONG) < 0 && big.compareTo(MIN_LONG) > 0) {
574 Int64Value iv = new Int64Value(big.longValue());
575 return iv.hashCode();
576 }
577 return big.hashCode();
578 }
579 }
580
581 /**
582 * Reduce a value to its simplest form.
583 */
584
585 /*@NotNull*/
586 public IntegerValue reduce() {
587 if (compareTo(Long.MAX_VALUE) < 0 && compareTo(Long.MIN_VALUE) > 0) {
588 Int64Value iv = new Int64Value(longValue());
589 iv.setTypeLabel(typeLabel);
590 return iv;
591 }
592 return this;
593 }
594
595 // /**
596 // * Convert to Java object (for passing to external functions)
597 // *
598 // * @param target The Java class to which conversion is required
599 // * @exception XPathException if conversion is not possible, or fails
600 // * @return the Java object that results from the conversion; always an
601 // * instance of the target class
602 /// */
603
604 // public Object convertAtomicToJava(Class target, XPathContext context) throws XPathException {
605 // if (isWithinLongRange()) {
606 // Int64Value val = Int64Value.makeIntegerValue(longValue());
607 // return val.convertToJava(target, context);
608 // } else if (target.isAssignableFrom(Int64Value.class)) {
609 // return this;
610 // } else if (target == BigInteger.class) {
611 // return value;
612 // } else {
613 // return convertPrimitive(BuiltInAtomicType.DECIMAL, true, context).asAtomic().convertToJava(target, context);
614 // }
615 // }
616
617 public BigIntegerValue asAtomic() {
618 return this;
619 }
620
621
622 }
623