Debian Codegraph @

net/sf/saxon/value/DayTimeDurationValue.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.sort.AtomicMatchKey;
11 import net.sf.saxon.lib.StringCollator;
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
20 /**
21 * A value of type xs:dayTimeDuration.
22 * <p>Internally this is held as an integer number of seconds held in a positive long, a positive integer
23 * number of microseconds in the range 0 to 999,999,999, and a boolean sign. Some of the constructor
24 * and accessor methods cannot handle the full range of values.</p>
25 */
26
27 public final class DayTimeDurationValue extends DurationValue
28 implements Comparable<DayTimeDurationValue> {
29
30 /**
31 * Private constructor for internal use
32 */
33
34 private DayTimeDurationValue() {
35 typeLabel = BuiltInAtomicType.DAY_TIME_DURATION;
36 }
37
38 /**
39 * Factory method: create a duration value from a supplied string, in
40 * ISO 8601 format {@code [-]PnDTnHnMnS}
41 *
42 * @param s the lexical representation of the xs:dayTimeDuration value
43 * @return a {@code DayTimeDurationValue} if the format is correct, or a {@link ValidationFailure} if not
44 */
45
46 public static ConversionResult makeDayTimeDurationValue(CharSequence s) {
47 ConversionResult d = DurationValue.makeDuration(s, false, true);
48 if (d instanceof ValidationFailure) {
49 return d;
50 }
51 DurationValue dv = (DurationValue) d;
52 return Converter.DurationToDayTimeDuration.INSTANCE.convert(dv);
53 }
54
55 /**
56 * Create a dayTimeDuration given the number of days, hours, minutes, and seconds. This
57 * constructor performs limited validation. The components (apart from sign) must all be non-negative
58 * integers; they need not be normalized (for example, 36 hours is acceptable)
59 * <p>Note: for historic reasons this constructor only supports microsecond precision. For nanosecond
60 * precision, use the constructor {@link DayTimeDurationValue#DayTimeDurationValue(int, int, int, long, int)}</p>
61 *
62 * @param sign positive number for positive durations, negative for negative duratoins
63 * @param days number of days
64 * @param hours number of hours
65 * @param minutes number of minutes
66 * @param seconds number of seconds
67 * @param microseconds number of microseconds
68 * @throws IllegalArgumentException if the value is out of range; specifically, if the total
69 * number of seconds exceeds 2^63; or if any of the values is negative
70 */
71
72 public DayTimeDurationValue(int sign, int days, int hours, int minutes, long seconds, int microseconds)
73 throws IllegalArgumentException {
74 if (days < 0 || hours < 0 || minutes < 0 || seconds < 0 || microseconds < 0) {
75 throw new IllegalArgumentException("Negative component value");
76 }
77 if ((double) days * (24 * 60 * 60) + (double) hours * (60 * 60) +
78 (double) minutes * 60 + (double) seconds > Long.MAX_VALUE) {
79 throw new IllegalArgumentException("Duration seconds limit exceeded");
80 }
81 negative = sign < 0;
82 months = 0;
83 long h = (long) days * 24L + (long) hours;
84 long m = h * 60L + (long) minutes;
85 long s = m * 60L + seconds;
86 if (microseconds > 1000000) {
87 s += microseconds / 1000000;
88 microseconds %= 1000000;
89 }
90 this.seconds = s;
91 this.nanoseconds = microseconds*1000;
92 if (s == 0 && microseconds == 0) {
93 negative = false;
94 }
95 typeLabel = BuiltInAtomicType.DAY_TIME_DURATION;
96 }
97
98 /**
99 * Create a dayTimeDuration given the number of days, hours, minutes, seconds, and nanoseconds. This
100 * constructor performs limited validation. The components need not be normalized (for example,
101 * 36 hours is acceptable)
102 * <p>To construct a positive duration, all the component values should be positive integers (or zero).
103 * To construct a negative duration, all the component values should be negative integers (or zero).</p>
104 *
105 * @param days number of days
106 * @param hours number of hours
107 * @param minutes number of minutes
108 * @param seconds number of seconds
109 * @param nanoseconds number of nanoseconds
110 * @throws IllegalArgumentException if the value is out of range; specifically, if the total
111 * number of seconds exceeds 2^63; or if some values are positive and
112 * others are negative
113 */
114
115 public DayTimeDurationValue(int days, int hours, int minutes, long seconds, int nanoseconds)
116 throws IllegalArgumentException {
117 boolean somePositive = days > 0 || hours > 0 || minutes > 0 || seconds > 0 || nanoseconds > 0;
118 boolean someNegative = days < 0 || hours < 0 || minutes < 0 || seconds < 0 || nanoseconds < 0;
119 if (somePositive && someNegative) {
120 throw new IllegalArgumentException("Some component values are positive and others are negative");
121 }
122 if (someNegative) {
123 negative = true;
124 days = -days;
125 hours = -hours;
126 minutes = -minutes;
127 seconds = -seconds;
128 nanoseconds = -nanoseconds;
129 }
130 if ((double) days * (24 * 60 * 60) + (double) hours * (60 * 60) +
131 (double) minutes * 60 + (double) seconds > Long.MAX_VALUE) {
132 throw new IllegalArgumentException("Duration seconds limit exceeded");
133 }
134 months = 0;
135 long h = (long) days * 24L + (long) hours;
136 long m = h * 60L + (long) minutes;
137 long s = m * 60L + seconds;
138 if (nanoseconds > 1_000_000_000) {
139 s += nanoseconds / 1_000_000_000;
140 nanoseconds %= 1_000_000_000;
141 }
142 this.seconds = s;
143 this.nanoseconds = nanoseconds;
144 typeLabel = BuiltInAtomicType.DAY_TIME_DURATION;
145 }
146
147 /**
148 * Create a copy of this atomic value, with a different type label
149 *
150 * @param typeLabel the type label of the new copy. The caller is responsible for checking that
151 * the value actually conforms to this type.
152 */
153
154 /*@NotNull*/
155 public AtomicValue copyAsSubType(AtomicType typeLabel) {
156 DayTimeDurationValue v = DayTimeDurationValue.fromSeconds(getTotalSeconds());
157 v.typeLabel = typeLabel;
158 return v;
159 }
160
161 /**
162 * Determine the primitive type of the value. This delivers the same answer as
163 * getItemType().getPrimitiveItemType(). The primitive types are
164 * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration,
165 * and xs:untypedAtomic. For external objects, the result is AnyAtomicType.
166 */
167
168 public BuiltInAtomicType getPrimitiveType() {
169 return BuiltInAtomicType.DAY_TIME_DURATION;
170 }
171
172 /**
173 * Convert to string
174 *
175 * @return ISO 8601 representation.
176 */
177
178 public CharSequence getPrimitiveStringValue() {
179
180 FastStringBuffer sb = new FastStringBuffer(32);
181 if (negative) {
182 sb.append('-');
183 }
184
185 int days = getDays();
186 int hours = getHours();
187 int minutes = getMinutes();
188 int seconds = getSeconds();
189
190 sb.append('P');
191 if (days != 0) {
192 sb.append(days + "D");
193 }
194 if (days == 0 || hours != 0 || minutes != 0 || seconds != 0 || nanoseconds != 0) {
195 sb.append('T');
196 }
197 if (hours != 0) {
198 sb.append(hours + "H");
199 }
200 if (minutes != 0) {
201 sb.append(minutes + "M");
202 }
203 if (seconds != 0 || nanoseconds != 0 || (days == 0 && minutes == 0 && hours == 0)) {
204 if (nanoseconds == 0) {
205 sb.append(seconds + "S");
206 } else {
207 long ms = (seconds * 1_000_000_000L) + nanoseconds;
208 String mss = ms + "";
209 if (seconds == 0) {
210 mss = "0000000000" + mss;
211 mss = mss.substring(mss.length() - 10);
212 }
213 sb.append(mss.substring(0, mss.length() - 9));
214 sb.append('.');
215 int lastSigDigit = mss.length() - 1;
216 while (mss.charAt(lastSigDigit) == '0') {
217 lastSigDigit--;
218 }
219 sb.append(mss.substring(mss.length() - 9, lastSigDigit + 1));
220 sb.append('S');
221 }
222 }
223 return sb;
224 }
225
226 /**
227 * Get the length of duration in seconds. Note this may involve loss of precision. For an exact
228 * result, use {@link #getTotalSeconds()}
229 * @return an approximation to the length of the duration in seconds, expressed as a double.
230 */
231
232 public double getLengthInSeconds() {
233 double a = seconds + ((double) nanoseconds / 1_000_000_000);
234 // System.err.println("Duration length " + days + "/" + hours + "/" + minutes + "/" + seconds + " is " + a);
235 return negative ? -a : a;
236 }
237
238 /**
239 * Get the length of duration in microseconds, as a long
240 *
241 * @return the length in nanoseconds, divided by one thousand, rounded towards zero
242 * @throws ArithmeticException if the number of microseconds is too high to be returned as a long.
243 */
244
245 public long getLengthInMicroseconds() {
246 if (seconds > Long.MAX_VALUE/1_000_000L) {
247 throw new ArithmeticException("Value is too large to be expressed in microseconds");
248 }
249 long a = seconds * 1_000_000L + (nanoseconds / 1000);
250 return negative ? -a : a;
251 }
252
253 /**
254 * Get the length of duration in microseconds, as a long
255 *
256 * @return the length in nanoseconds, divided by one thousand, rounded towards zero
257 * @throws ArithmeticException if the number of nanoseconds is too high to be returned as a long.
258 */
259
260 public long getLengthInNanoseconds() {
261 if (seconds > Long.MAX_VALUE / 1_000_000_000L) {
262 throw new ArithmeticException("Value is too large to be expressed in nanoseconds");
263 }
264 long a = seconds * 1_000_000_000L + nanoseconds;
265 return negative ? -a : a;
266 }
267
268
269 /**
270 * Construct a duration value as a number of seconds.
271 *
272 * @param seconds the number of seconds in the duration. May be negative
273 * @return the xs:dayTimeDuration value with the specified length
274 * @throws ArithmeticException if the number of (whole) seconds exceeds 2^63
275 */
276
277 public static DayTimeDurationValue fromSeconds(BigDecimal seconds) {
278 DayTimeDurationValue sdv = new DayTimeDurationValue();
279 sdv.negative = seconds.signum() < 0;
280 if (sdv.negative) {
281 seconds = seconds.negate();
282 }
283 BigInteger wholeSeconds = seconds.toBigInteger();
284 sdv.seconds = wholeSeconds.longValueExact(); // ArithmeticException if out of range
285 BigDecimal fractionalPart = seconds.remainder(BigDecimal.ONE);
286 BigDecimal nanoseconds = fractionalPart.multiply(BigDecimalValue.BIG_DECIMAL_ONE_BILLION);
287 sdv.nanoseconds = nanoseconds.intValue();
288 if (sdv.seconds == 0 && sdv.nanoseconds == 0) {
289 // can happen with underflow (division by a very large number)
290 sdv.negative = false;
291 }
292 return sdv;
293 }
294
295
296
297 /**
298 * Construct a duration value as a number of milliseconds.
299 *
300 * @param milliseconds the number of milliseconds in the duration (may be negative)
301 * @return the corresponding xs:dayTimeDuration value
302 * @throws ValidationException if implementation-defined limits are exceeded, specifically
303 * if the total number of seconds exceeds 2^63.
304 */
305
306 public static DayTimeDurationValue fromMilliseconds(long milliseconds) throws ValidationException {
307 int sign = Long.signum(milliseconds);
308 if (sign < 0) {
309 milliseconds = -milliseconds;
310 }
311 try {
312 return new DayTimeDurationValue(
313 sign, 0, 0, 0, milliseconds / 1000, (int) (milliseconds % 1000) * 1000);
314 } catch (IllegalArgumentException err) {
315 // limits exceeded
316 throw new ValidationFailure("Duration exceeds limits").makeException();
317 }
318 }
319
320 /**
321 * Construct a duration value as a number of microseconds.
322 *
323 * @param microseconds the number of microseconds in the duration.
324 * @return the xs:dayTimeDuration represented by the given number of microseconds
325 */
326
327 public static DayTimeDurationValue fromMicroseconds(long microseconds) throws IllegalArgumentException {
328 int sign = Long.signum(microseconds);
329 if (sign < 0) {
330 microseconds = -microseconds;
331 }
332 return new DayTimeDurationValue(
333 sign, 0, 0, 0, microseconds / 1_000_000, (int) (microseconds % 1_000_000));
334
335 }
336
337 /**
338 * Construct a duration value as a number of nanoseconds.
339 *
340 * @param nanoseconds the number of nanoseconds in the duration.
341 * @return the xs:dayTimeDuration represented by the given number of nanoseconds
342 */
343
344 public static DayTimeDurationValue fromNanoseconds(long nanoseconds) throws IllegalArgumentException {
345 int sign = Long.signum(nanoseconds);
346 return new DayTimeDurationValue(
347 0, 0, 0, nanoseconds / 1_000_000_000L, (int) (nanoseconds % 1_000_000_000L));
348 }
349
350 /**
351 * Factory method taking a Java 8 {@link java.time.Duration} object
352 * @param duration a duration as a Java 8 {@code java.time.Duration}
353 * @since 9.9
354 */
355
356 public static DayTimeDurationValue fromJavaDuration(java.time.Duration duration) {
357 long seconds = duration.getSeconds();
358 int nanoseconds = duration.getNano();
359 boolean negative = false;
360 if (seconds < 0) {
361 return new DayTimeDurationValue(0, 0, 0, seconds, -1_000_000_000 + nanoseconds);
362 } else {
363 return new DayTimeDurationValue(0, 0, 0, seconds, nanoseconds);
364 }
365 }
366
367 /**
368 * Convert this value to a Java 8 {@link java.time.Duration} object
369 * @return the duration expressed as a Java 8 {@code java.time.Duration}
370 * @since 9.9
371 */
372
373 public java.time.Duration toJavaDuration() {
374 if (negative) {
375 return java.time.Duration.ofSeconds(-seconds, -nanoseconds);
376 } else {
377 return java.time.Duration.ofSeconds(seconds, nanoseconds);
378 }
379 }
380
381
382 /**
383 * Multiply a duration by an integer
384 *
385 * @param factor the number to multiply by
386 * @return the result of the multiplication
387 */
388
389 public DurationValue multiply(long factor) throws XPathException {
390 // Fast path for simple cases
391 if (Math.abs(factor) < 0x7fff_ffff && Math.abs(seconds) < 0x7fff_ffff) {
392 return new DayTimeDurationValue(0, 0, 0,
393 seconds * factor * (negative ? -1 : 1),
394 (int)(nanoseconds * factor * (negative ? -1 : 1)));
395 } else {
396 return multiply(BigDecimal.valueOf(factor));
397 }
398 }
399
400
401 /**
402 * Multiply duration by a number. Follows the semantics of op:multiply-dayTimeDuration.
403 * @param n the number to multiply by.
404 * @throws XPathException if the operand is Infinite or NaN, or if the resulting duration
405 * exceeds Saxon limits (2^63 seconds)
406 */
407
408 public DayTimeDurationValue multiply(double n) throws XPathException {
409 if (Double.isNaN(n)) {
410 XPathException err = new XPathException("Cannot multiply a duration by NaN");
411 err.setErrorCode("FOCA0005");
412 throw err;
413 }
414 if (Double.isInfinite(n)) {
415 XPathException err = new XPathException("Cannot multiply a duration by infinity");
416 err.setErrorCode("FODT0002");
417 throw err;
418 }
419 BigDecimal factor = BigDecimal.valueOf(n);
420 return multiply(factor);
421 }
422
423 private DayTimeDurationValue multiply(BigDecimal factor) throws XPathException {
424 BigDecimal secs = getTotalSeconds();
425 BigDecimal product = secs.multiply(factor);
426 try {
427 return fromSeconds(product);
428 } catch (IllegalArgumentException | ArithmeticException err) {
429 if (err.getCause() instanceof XPathException) {
430 throw (XPathException) err.getCause();
431 } else {
432 XPathException err2 = new XPathException("Overflow when multiplying a duration by a number", err);
433 err2.setErrorCode("FODT0002");
434 throw err2;
435 }
436 }
437 }
438
439 /**
440 * Divide duration by a number. Follows the semantics of op:divide-dayTimeDuration.
441 *
442 * @param n the number to divide by.
443 * @throws XPathException if the operand is zero or NaN, or if the resulting duration
444 * exceeds Saxon limits (2^63 seconds)
445 */
446
447 public DurationValue divide(double n) throws XPathException {
448 if (Double.isNaN(n)) {
449 XPathException err = new XPathException("Cannot divide a duration by NaN");
450 err.setErrorCode("FOCA0005");
451 throw err;
452 }
453 if (n == 0) {
454 XPathException err = new XPathException("Cannot divide a duration by zero");
455 err.setErrorCode("FODT0002");
456 throw err;
457 }
458 BigDecimal secs = getTotalSeconds();
459 BigDecimal product = secs.divide(BigDecimal.valueOf(n));
460 try {
461 return fromSeconds(product);
462 } catch (IllegalArgumentException | ArithmeticException err) {
463 if (err.getCause() instanceof XPathException) {
464 throw (XPathException) err.getCause();
465 } else {
466 XPathException err2 = new XPathException("Overflow when dividing a duration by a number", err);
467 err2.setErrorCode("FODT0002");
468 throw err2;
469 }
470 }
471 }
472
473 /**
474 * Find the ratio between two durations
475 *
476 * @param other the dividend
477 * @return the ratio, as a decimal
478 * @throws XPathException when dividing by zero, or when dividing two durations of different type
479 */
480 public BigDecimalValue divide(DurationValue other) throws XPathException {
481 if (other instanceof DayTimeDurationValue) {
482 BigDecimal v1 = getTotalSeconds();
483 BigDecimal v2 = other.getTotalSeconds();
484 if (v2.signum() == 0) {
485 XPathException err = new XPathException("Divide by zero (durations)");
486 err.setErrorCode("FOAR0001");
487 throw err;
488 }
489 return new BigDecimalValue(v1.divide(v2, 20, RoundingMode.HALF_EVEN));
490 } else {
491 XPathException err = new XPathException("Cannot divide two durations of different type");
492 err.setErrorCode("XPTY0004");
493 throw err;
494 }
495 }
496
497 /**
498 * Add two dayTimeDurations
499 */
500
501 public DurationValue add(DurationValue other) throws XPathException {
502 if (other instanceof DayTimeDurationValue) {
503 DayTimeDurationValue d2 = (DayTimeDurationValue)other;
504 if (((seconds | d2.seconds) & 0xffff_ffff_0000_0000L) != 0) {
505 // risk of complications, use BigDecimal arithmetic
506 try {
507 BigDecimal v1 = getTotalSeconds();
508 BigDecimal v2 = other.getTotalSeconds();
509 return fromSeconds(v1.add(v2));
510 } catch (IllegalArgumentException e) {
511 XPathException err = new XPathException("Overflow when adding two durations");
512 err.setErrorCode("FODT0002");
513 throw err;
514 }
515 } else {
516 // fast path for common case: no risk of overflow
517 return DayTimeDurationValue.fromNanoseconds(getLengthInNanoseconds() + d2.getLengthInNanoseconds());
518 }
519 } else {
520 XPathException err = new XPathException("Cannot add two durations of different type");
521 err.setErrorCode("XPTY0004");
522 throw err;
523 }
524 }
525
526 /**
527 * Subtract two dayTime-durations
528 */
529
530 public DurationValue subtract(DurationValue other) throws XPathException {
531 if (other instanceof DayTimeDurationValue) {
532 DayTimeDurationValue d2 = (DayTimeDurationValue) other;
533 if (((seconds | d2.seconds) & 0xffff_ffff_0000_0000L) != 0) {
534 // risk of complications, use BigDecimal arithmetic
535 try {
536 BigDecimal v1 = getTotalSeconds();
537 BigDecimal v2 = other.getTotalSeconds();
538 return fromSeconds(v1.subtract(v2));
539 } catch (IllegalArgumentException e) {
540 XPathException err = new XPathException("Overflow when subtracting two durations");
541 err.setErrorCode("FODT0002");
542 throw err;
543 }
544 } else {
545 // fast path for common case: no risk of overflow
546 return DayTimeDurationValue.fromNanoseconds(getLengthInNanoseconds() - d2.getLengthInNanoseconds());
547 }
548 } else {
549 XPathException err = new XPathException("Cannot subtract two durations of different type");
550 err.setErrorCode("XPTY0004");
551 throw err;
552 }
553 }
554
555 /**
556 * Negate a duration (same as subtracting from zero, but it preserves the type of the original duration)
557 *
558 * @throws IllegalArgumentException in the extremely unlikely event that the duration is one that cannot
559 * be negated (because the limit for positive durations is one second
560 * off from the limit for negative durations)
561 */
562
563 public DurationValue negate() throws IllegalArgumentException {
564 DayTimeDurationValue d2 = new DayTimeDurationValue();
565 d2.setTypeLabel(typeLabel);
566 d2.seconds = seconds;
567 d2.nanoseconds = nanoseconds;
568 d2.negative = !negative;
569 return d2;
570 }
571
572 /**
573 * Compare the value to another duration value
574 *
575 * @param other The other dateTime value
576 * @return negative value if this one is the smaller, 0 if they are equal,
577 * positive value if this one is the greater.
578 * @throws ClassCastException if the other value is not a DayTimeDurationValue
579 */
580
581 public int compareTo(DayTimeDurationValue other) {
582 if (other instanceof DayTimeDurationValue) {
583 if (this.negative != other.negative) {
584 return this.negative ? -1 : +1;
585 } else if (this.seconds != other.seconds) {
586 return Long.compare(this.seconds, other.seconds) * (this.negative ? -1 : +1);
587 } else {
588 return Integer.compare(this.nanoseconds, other.nanoseconds) * (this.negative ? -1 : +1);
589 }
590 } else {
591 throw new ClassCastException("Cannot compare a dayTimeDuration to an object of class "
592 + other.getClass());
593 }
594 }
595
596 /**
597 * Get a Comparable value that implements the XPath ordering comparison semantics for this value.
598 * Returns null if the value is not comparable according to XPath rules. The default implementation
599 * returns the value itself. This is modified for types such as
600 * xs:duration which allow ordering comparisons in XML Schema, but not in XPath.
601 *
602 * @param ordered true if an ordered comparable is needed
603 * @param collator Collation used for string comparison
604 * @param implicitTimezone XPath dynamic context
605 */
606
607 public AtomicMatchKey getXPathComparable(boolean ordered, StringCollator collator, int implicitTimezone) {
608 return this;
609 }
610
611
612 }
613