Debian Codegraph @

net/sf/saxon/value/IntegerValue.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.parser.Location;
11 import net.sf.saxon.functions.FormatNumber;
12 import net.sf.saxon.om.StandardNames;
13 import net.sf.saxon.trans.Err;
14 import net.sf.saxon.trans.XPathException;
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 * This class represents the XPath built-in type xs:integer. It is used for all
24 * subtypes of xs:integer, other than user-defined subtypes. There are two implementations
25 * of IntegerValue: {@link Int64Value}, which accommodates values up to 2^63, and
26 * {@link BigIntegerValue}, which accommodates unlimited-length integers.
27 * @since 9.8: changed in 9.8 to make this class a subclass of the new abstract
28 * class DecimalValue, to better reflect the XDM type hierarchy
29 */
30
31 public abstract class IntegerValue extends DecimalValue {
32
33 /**
34 * Static data identifying the min and max values for each built-in subtype of xs:integer.
35 * This is a sequence of triples, each holding the fingerprint of the type, the minimum
36 * value, and the maximum value. The special value NO_LIMIT indicates that there is no
37 * minimum (or no maximum) for this type. The special value MAX_UNSIGNED_LONG represents the
38 * value 2^64-1
39 */
40 private static long NO_LIMIT = -9999;
41 private static long MAX_UNSIGNED_LONG = -9998;
42
43 /*@NotNull*/ private static long[] ranges = {
44 // arrange so the most frequently used types are near the start
45 StandardNames.XS_INTEGER, NO_LIMIT, NO_LIMIT,
46 StandardNames.XS_LONG, Long.MIN_VALUE, Long.MAX_VALUE,
47 StandardNames.XS_INT, Integer.MIN_VALUE, Integer.MAX_VALUE,
48 StandardNames.XS_SHORT, Short.MIN_VALUE, Short.MAX_VALUE,
49 StandardNames.XS_BYTE, Byte.MIN_VALUE, Byte.MAX_VALUE,
50 StandardNames.XS_NON_NEGATIVE_INTEGER, 0, NO_LIMIT,
51 StandardNames.XS_POSITIVE_INTEGER, 1, NO_LIMIT,
52 StandardNames.XS_NON_POSITIVE_INTEGER, NO_LIMIT, 0,
53 StandardNames.XS_NEGATIVE_INTEGER, NO_LIMIT, -1,
54 StandardNames.XS_UNSIGNED_LONG, 0, MAX_UNSIGNED_LONG,
55 StandardNames.XS_UNSIGNED_INT, 0, 4294967295L,
56 StandardNames.XS_UNSIGNED_SHORT, 0, 65535,
57 StandardNames.XS_UNSIGNED_BYTE, 0, 255};
58
59 /**
60 * Factory method: makes either an Int64Value or a BigIntegerValue depending on the value supplied
61 *
62 * @param value the supplied integer value
63 * @return the value as a BigIntegerValue or Int64Value as appropriate
64 */
65
66 public static IntegerValue makeIntegerValue(/*@NotNull*/ BigInteger value) {
67 if (value.compareTo(BigIntegerValue.MAX_LONG) > 0 || value.compareTo(BigIntegerValue.MIN_LONG) < 0) {
68 return new BigIntegerValue(value);
69 } else {
70 return Int64Value.makeIntegerValue(value.longValue());
71 }
72 }
73
74 /**
75 * Convert a double to an integer
76 *
77 * @param value the double to be converted
78 * @return the result of the conversion, or the validation failure if the input is NaN or infinity
79 */
80
81 public static ConversionResult makeIntegerValue(double value) {
82 if (Double.isNaN(value)) {
83 ValidationFailure err = new ValidationFailure("Cannot convert double NaN to an integer");
84 err.setErrorCode("FOCA0002");
85 return err;
86 }
87 if (Double.isInfinite(value)) {
88 ValidationFailure err = new ValidationFailure("Cannot convert double INF to an integer");
89 err.setErrorCode("FOCA0002");
90 return err;
91 }
92 if (value > Long.MAX_VALUE || value < Long.MIN_VALUE) {
93 if (value == Math.floor(value)) {
94 return new BigIntegerValue(FormatNumber.adjustToDecimal(value, 2).toBigInteger());
95 } else {
96 return new BigIntegerValue(new BigDecimal(value).toBigInteger());
97 }
98 }
99 return Int64Value.makeIntegerValue((long) value);
100 }
101
102 /**
103 * Convert a double to an integer
104 *
105 * @param doubleValue the double to be converted
106 * @return the result of the conversion, or the validation failure if the input is NaN or infinity
107 */
108
109 public static ConversionResult makeIntegerValue(DoubleValue doubleValue) {
110 double value = doubleValue.getDoubleValue();
111 return makeIntegerValue(value);
112 }
113
114 /**
115 * This class allows subtypes of xs:integer to be held, as well as xs:integer values.
116 * This method sets the required type label. Note that this method modifies the value in situ.
117 *
118 * @param type the subtype of integer required
119 * @param validate true if validation is required, false if the caller warrants that the value
120 * is valid for the subtype
121 * @return null if the operation succeeds, or a ValidationException if the value is out of range
122 */
123
124 /*@Nullable*/
125 public abstract ValidationFailure convertToSubType(BuiltInAtomicType type, boolean validate);
126
127 /**
128 * This class allows subtypes of xs:integer to be held, as well as xs:integer values.
129 * This method sets the required type label. Note that this method modifies the value in situ.
130 *
131 * @param type the subtype of integer required
132 * @return null if the operation succeeds, or a ValidationException if the value is out of range
133 */
134
135 /*@Nullable*/
136 public abstract ValidationFailure validateAgainstSubType(BuiltInAtomicType type);
137
138 /**
139 * Check that a value is in range for the specified subtype of xs:integer
140 *
141 * @param value the value to be checked
142 * @param type the required item type, a subtype of xs:integer
143 * @return true if successful, false if value is out of range for the subtype
144 */
145
146 public static boolean checkRange(long value, /*@NotNull*/ BuiltInAtomicType type) {
147 int fp = type.getFingerprint();
148 for (int i = 0; i < ranges.length; i += 3) {
149 if (ranges[i] == fp) {
150 long min = ranges[i + 1];
151 if (min != NO_LIMIT && value < min) {
152 return false;
153 }
154 long max = ranges[i + 2];
155 return max == NO_LIMIT || max == MAX_UNSIGNED_LONG || value <= max;
156 }
157 }
158 throw new IllegalArgumentException(
159 "No range information found for integer subtype " + type.getDescription());
160 }
161
162 /**
163 * Get the minInclusive facet for a built-in integer subtype
164 *
165 * @param type the built-in type, which must be derived from xs:integer
166 * @return the value of the minInclusive facet if there is a lower limit, or null if not
167 */
168
169 public static IntegerValue getMinInclusive(BuiltInAtomicType type) {
170 int fp = type.getFingerprint();
171 for (int i = 0; i < ranges.length; i += 3) {
172 if (ranges[i] == fp) {
173 long min = ranges[i + 1];
174 if (min == NO_LIMIT) {
175 return null;
176 } else {
177 return Int64Value.makeIntegerValue(min);
178 }
179 }
180 }
181 return null;
182 }
183
184 /**
185 * Get the maxInclusive facet for a built-in integer subtype
186 *
187 * @param type the built-in type, which must be derived from xs:integer
188 * @return the value of the minInclusive facet if there is a lower limit, or null if not
189 */
190
191 public static IntegerValue getMaxInclusive(BuiltInAtomicType type) {
192 int fp = type.getFingerprint();
193 for (int i = 0; i < ranges.length; i += 3) {
194 if (ranges[i] == fp) {
195 long max = ranges[i + 2];
196 if (max == NO_LIMIT) {
197 return null;
198 } else if (max == MAX_UNSIGNED_LONG) {
199 return IntegerValue.makeIntegerValue(BigIntegerValue.MAX_UNSIGNED_LONG);
200 } else {
201 return Int64Value.makeIntegerValue(max);
202 }
203 }
204 }
205 return null;
206 }
207
208 /**
209 * Check that a BigInteger is within the required range for a given integer subtype.
210 * This method is expensive, so it should not be used unless the BigInteger is outside the range of a long.
211 *
212 * @param big the supplied BigInteger
213 * @param type the derived type (a built-in restriction of xs:integer) to check the value against
214 * @return true if the value is within the range for the derived type
215 */
216
217 public static boolean checkBigRange(BigInteger big, /*@NotNull*/ BuiltInAtomicType type) {
218
219 for (int i = 0; i < ranges.length; i += 3) {
220 if (ranges[i] == type.getFingerprint()) {
221 long min = ranges[i + 1];
222 if (min != NO_LIMIT && BigInteger.valueOf(min).compareTo(big) > 0) {
223 return false;
224 }
225 long max = ranges[i + 2];
226 if (max == NO_LIMIT) {
227 return true;
228 } else if (max == MAX_UNSIGNED_LONG) {
229 return BigIntegerValue.MAX_UNSIGNED_LONG.compareTo(big) >= 0;
230 } else {
231 return BigInteger.valueOf(max).compareTo(big) >= 0;
232 }
233 }
234 }
235 throw new IllegalArgumentException(
236 "No range information found for integer subtype " + type.getDescription());
237 }
238
239 /**
240 * Static factory method to convert strings to integers.
241 *
242 * @param s CharSequence representing the string to be converted
243 * @return either an Int64Value or a BigIntegerValue representing the value of the String, or
244 * a ValidationFailure encapsulating an Exception if the value cannot be converted.
245 */
246
247 public static ConversionResult stringToInteger(/*@NotNull*/ CharSequence s) {
248
249 int len = s.length();
250 int start = 0;
251 int last = len - 1;
252 while (start < len && s.charAt(start) <= 0x20) {
253 start++;
254 }
255 while (last > start && s.charAt(last) <= 0x20) {
256 last--;
257 }
258 if (start > last) {
259 return new ValidationFailure("Cannot convert zero-length string to an integer");
260 }
261 if (last - start < 16) {
262 // for short numbers, we do the conversion ourselves, to avoid throwing unnecessary exceptions
263 boolean negative = false;
264 long value = 0;
265 int i = start;
266 if (s.charAt(i) == '+') {
267 i++;
268 } else if (s.charAt(i) == '-') {
269 negative = true;
270 i++;
271 }
272 if (i > last) {
273 return new ValidationFailure("Cannot convert string " + Err.wrap(s, Err.VALUE) +
274 " to integer: no digits after the sign");
275 }
276 while (i <= last) {
277 char d = s.charAt(i++);
278 if (d >= '0' && d <= '9') {
279 value = 10 * value + (d - '0');
280 } else {
281 return new ValidationFailure("Cannot convert string " + Err.wrap(s, Err.VALUE) + " to an integer");
282 }
283 }
284 return Int64Value.makeIntegerValue(negative ? -value : value);
285 } else {
286 // for longer numbers, rely on library routines
287 try {
288 CharSequence t = Whitespace.trimWhitespace(s);
289 if (t.charAt(0) == '+') {
290 t = t.subSequence(1, t.length());
291 }
292 if (t.length() < 16) {
293 return new Int64Value(Long.parseLong(t.toString()));
294 } else {
295 return new BigIntegerValue(new BigInteger(t.toString()));
296 }
297 } catch (NumberFormatException err) {
298 return new ValidationFailure("Cannot convert string " + Err.wrap(s, Err.VALUE) + " to an integer");
299 }
300 }
301 }
302
303 /**
304 * Determine whether a string is castable as an integer
305 *
306 * @param input the string to be tested
307 * @return null if the string is castable to an integer, or a validation failure otherwise
308 */
309
310 /*@Nullable*/
311 public static ValidationFailure castableAsInteger(CharSequence input) {
312 CharSequence s = Whitespace.trimWhitespace(input);
313
314 int last = s.length() - 1;
315 if (last < 0) {
316 return new ValidationFailure("Cannot convert empty string to an integer");
317 }
318 int i = 0;
319 if (s.charAt(i) == '+' || s.charAt(i) == '-') {
320 i++;
321 }
322 if (i > last) {
323 return new ValidationFailure("Cannot convert string " + Err.wrap(s, Err.VALUE) +
324 " to integer: no digits after the sign");
325 }
326 while (i <= last) {
327 char d = s.charAt(i++);
328 if (d >= '0' && d <= '9') {
329 // OK
330 } else {
331 return new ValidationFailure("Cannot convert string " + Err.wrap(s, Err.VALUE) + " to an integer: contains a character that is not a digit");
332 }
333 }
334 return null;
335 }
336
337 /**
338 * Determine the primitive type of the value. This delivers the same answer as
339 * getItemType().getPrimitiveItemType(). The primitive types are
340 * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration,
341 * and xs:untypedAtomic. For external objects, the result is AnyAtomicType.
342 */
343
344 /*@NotNull*/
345 public BuiltInAtomicType getPrimitiveType() {
346 return BuiltInAtomicType.INTEGER;
347 }
348
349 /**
350 * Get the numeric value converted to a decimal
351 *
352 * @return a decimal representing this numeric value;
353 */
354
355 public abstract BigDecimal getDecimalValue();
356
357 /**
358 * Determine whether the value is a whole number, that is, whether it compares
359 * equal to some integer
360 *
361 * @return always true for this implementation
362 */
363
364 public boolean isWholeNumber() {
365 return true;
366 }
367
368 /**
369 * Add another integer
370 *
371 * @param other the other integer
372 * @return the result of the addition
373 */
374
375 public abstract IntegerValue plus(IntegerValue other);
376
377 /**
378 * Subtract another integer
379 *
380 * @param other the other integer
381 * @return the result of the subtraction
382 */
383
384 public abstract IntegerValue minus(IntegerValue other);
385
386 /**
387 * Multiply by another integer
388 *
389 * @param other the other integer
390 * @return the result of the multiplication
391 */
392
393 public abstract IntegerValue times(IntegerValue other);
394
395 /**
396 * Divide by another integer
397 *
398 * @param other the other integer
399 * @return the result of the division
400 * @throws XPathException if the other integer is zero
401 */
402
403 public abstract NumericValue div(IntegerValue other) throws XPathException;
404
405 /**
406 * Divide by another integer, providing location information for any exception
407 *
408 * @param other the other integer
409 * @param locator the location of the expression, for use in diagnostics
410 * @return the result of the division
411 * @throws XPathException if the other integer is zero
412 */
413
414 public NumericValue div(IntegerValue other, Location locator) throws XPathException {
415 try {
416 return div(other);
417 } catch (XPathException err) {
418 err.maybeSetLocation(locator);
419 throw err;
420 }
421 }
422
423 /**
424 * Take modulo another integer
425 *
426 * @param other the other integer
427 * @return the result of the modulo operation (the remainder)
428 * @throws XPathException if the other integer is zero
429 */
430
431 public abstract IntegerValue mod(IntegerValue other) throws XPathException;
432
433 /**
434 * Take modulo another integer, providing location information for any exception
435 *
436 * @param other the other integer
437 * @param locator the location of the expression, for use in diagnostics
438 * @return the result of the division
439 * @throws XPathException if the other integer is zero
440 */
441
442 public IntegerValue mod(IntegerValue other, Location locator) throws XPathException {
443 try {
444 return mod(other);
445 } catch (XPathException err) {
446 err.maybeSetLocation(locator);
447 throw err;
448 }
449 }
450
451 /**
452 * Integer divide by another integer
453 *
454 * @param other the other integer
455 * @return the result of the integer division
456 * @throws XPathException if the other integer is zero
457 */
458
459 public abstract IntegerValue idiv(IntegerValue other) throws XPathException;
460
461 /**
462 * Integer divide by another integer, providing location information for any exception
463 *
464 * @param other the other integer
465 * @param locator the location of the expression, for use in diagnostics
466 * @return the result of the division
467 * @throws XPathException if the other integer is zero
468 */
469
470 public IntegerValue idiv(IntegerValue other, Location locator) throws XPathException {
471 try {
472 return idiv(other);
473 } catch (XPathException err) {
474 err.maybeSetLocation(locator);
475 throw err;
476 }
477 }
478
479 /**
480 * Get the value as a BigInteger
481 *
482 * @return the value, as a BigInteger
483 */
484
485 public abstract BigInteger asBigInteger();
486
487 /**
488 * Get the signum of an int
489 *
490 * @param i the int
491 * @return -1 if the integer is negative, 0 if it is zero, +1 if it is positive
492 */
493
494 protected static int signum(int i) {
495 return (i >> 31) | (-i >>> 31);
496 }
497
498 /**
499 * Determine whether two atomic values are identical, as determined by XML Schema rules. This is a stronger
500 * test than equality (even schema-equality); for example two dateTime values are not identical unless
501 * they are in the same timezone.
502 * <p>Note that even this check ignores the type annotation of the value. The integer 3 and the short 3
503 * are considered identical, even though they are not fully interchangeable. "Identical" means the
504 * same point in the value space, regardless of type annotation.</p>
505 * <p>NaN is identical to itself.</p>
506 *
507 * @param v the other value to be compared with this one
508 * @return true if the two values are identical, false otherwise.
509 */
510
511 public boolean isIdentical(/*@NotNull*/ AtomicValue v) {
512 return (v instanceof IntegerValue) && equals(v);
513 }
514
515
516 }
517