Debian Codegraph @

net/sf/saxon/value/DurationValue.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.functions.AccessorFn;
12 import net.sf.saxon.lib.StringCollator;
13 import net.sf.saxon.om.SequenceTool;
14 import net.sf.saxon.trans.XPathException;
15 import net.sf.saxon.tree.util.FastStringBuffer;
16 import net.sf.saxon.type.AtomicType;
17 import net.sf.saxon.type.BuiltInAtomicType;
18 import net.sf.saxon.type.ConversionResult;
19 import net.sf.saxon.type.ValidationFailure;
20
21 import java.math.BigDecimal;
22 import java.math.BigInteger;
23 import java.util.StringTokenizer;
24
25 /**
26 * A value of type xs:duration
27 */
28
29 public class DurationValue extends AtomicValue implements AtomicMatchKey {
30
31 protected boolean negative = false;
32 protected int months = 0;
33 protected long seconds = 0;
34 protected int nanoseconds = 0;
35
36 /**
37 * Private constructor for internal use
38 */
39
40 protected DurationValue() {
41 }
42
43 /**
44 * Constructor for xs:duration taking the components of the duration. There is no requirement
45 * that the values are normalized, for example it is acceptable to specify months=18. The values of
46 * the individual components must all be non-negative.
47 * <p>Note: For historic reasons this constructor only supports microsecond precision. To get nanosecond
48 * precision, use the constructor {@link DurationValue#DurationValue(int, int, int, int, int, long, int, AtomicType)}.</p>
49 *
50 * @param positive true if the duration is positive, false if negative. For a negative duration
51 * the components are all supplied as positive integers (or zero).
52 * @param years the number of years
53 * @param months the number of months
54 * @param days the number of days
55 * @param hours the number of hours
56 * @param minutes the number of minutes
57 * @param seconds the number of seconds
58 * @param microseconds the number of microseconds
59 * @throws IllegalArgumentException if the size of the duration exceeds implementation-defined
60 * limits: specifically, if the total number of months exceeds 2^31, or if the total number
61 * of seconds exceeds 2^63.
62 */
63
64 public DurationValue(boolean positive, int years, int months, int days,
65 int hours, int minutes, long seconds, int microseconds)
66 throws IllegalArgumentException {
67 this(positive, years, months, days, hours, minutes, seconds, microseconds, BuiltInAtomicType.DURATION);
68 }
69
70 /**
71 * Constructor for xs:duration taking the components of the duration, plus a user-specified
72 * type which must be a subtype of xs:duration. There is no requirement
73 * that the values are normalized, for example it is acceptable to specify months=18. The values of
74 * the individual components must all be non-negative.
75 * <p>Note: for historic reasons this constructor was written to expect microseconds rather than nanoseconds.
76 * To supply nanoseconds, use the alternative constructor
77 * {@link DurationValue#DurationValue(int, int, int, int, int, long, int, AtomicType)}.</p>
78 *
79 * @param positive true if the duration is positive, false if negative. For a negative duration
80 * the components are all supplied as positive integers (or zero).
81 * @param years the number of years
82 * @param months the number of months
83 * @param days the number of days
84 * @param hours the number of hours
85 * @param minutes the number of minutes
86 * @param seconds the number of seconds (long to allow copying)
87 * @param microseconds the number of microseconds
88 * @param type the user-defined subtype of xs:duration. Note that this constructor cannot
89 * be used to create an instance of xs:dayTimeDuration or xs:yearMonthDuration.
90 * @throws IllegalArgumentException if the size of the duration exceeds implementation-defined
91 * limits: specifically, if the total number of months exceeds 2^31, or if the total number
92 * of seconds exceeds 2^63.
93 */
94
95 public DurationValue(boolean positive, int years, int months, int days,
96 int hours, int minutes, long seconds, int microseconds, AtomicType type) {
97 negative = !positive;
98 if (years < 0 || months < 0 || days < 0 || hours < 0 || minutes < 0 || seconds < 0 || microseconds < 0) {
99 throw new IllegalArgumentException("Negative component value");
100 }
101 if ((double) years * 12 + (double) months > Integer.MAX_VALUE) {
102 throw new IllegalArgumentException("Duration months limit exceeded");
103 }
104 if ((double) days * (24 * 60 * 60) + (double) hours * (60 * 60) +
105 (double) minutes * 60 + (double) seconds > Long.MAX_VALUE) {
106 throw new IllegalArgumentException("Duration seconds limit exceeded");
107 }
108 this.months = years * 12 + months;
109 long h = days * 24L + hours;
110 long m = h * 60L + minutes;
111 this.seconds = m * 60L + seconds;
112 this.nanoseconds = microseconds * 1000;
113 normalizeZeroDuration();
114 typeLabel = type;
115 }
116
117 /**
118 * Constructor for xs:duration taking the components of the duration, plus a user-specified
119 * type which must be a subtype of xs:duration. There is no requirement
120 * that the values are normalized, for example it is acceptable to specify months=18. The values of
121 * the individual components must all be non-negative.
122 * <p>If the duration is positive, all the components must be supplied as positive (or zero) integers.
123 * If the duration is negative, all the components must be supplied as negative (or zero) integers.</p>
124 *
125 * @param years the number of years
126 * @param months the number of months
127 * @param days the number of days
128 * @param hours the number of hours
129 * @param minutes the number of minutes
130 * @param seconds the number of seconds (long to allow copying)
131 * @param nanoseconds the number of nanoseconds
132 * @param type the user-defined subtype of xs:duration. Note that this constructor cannot
133 * be used to create an instance of xs:dayTimeDuration or xs:yearMonthDuration.
134 * @throws IllegalArgumentException if the size of the duration exceeds implementation-defined
135 * limits: specifically, if the total number of months exceeds 2^31, or if the total number
136 * of seconds exceeds 2^63.
137 */
138
139 public DurationValue(int years, int months, int days,
140 int hours, int minutes, long seconds, int nanoseconds, AtomicType type) {
141 boolean somePositive = years > 0 || months > 0 || days > 0 || hours > 0 || minutes > 0 || seconds > 0 || nanoseconds > 0;
142 boolean someNegative = years < 0 || months < 0 || days < 0 || hours < 0 || minutes < 0 || seconds < 0 || nanoseconds < 0;
143 if (somePositive && someNegative) {
144 throw new IllegalArgumentException("Some component values are positive and some negative");
145 }
146 if (someNegative) {
147 years = -years;
148 months = -months;
149 days = -days;
150 hours = -hours;
151 minutes = -minutes;
152 seconds = -seconds;
153 nanoseconds = -nanoseconds;
154 }
155 if ((double) years * 12 + (double) months > Integer.MAX_VALUE) {
156 throw new IllegalArgumentException("Duration months limit exceeded");
157 }
158 if ((double) days * (24 * 60 * 60) + (double) hours * (60 * 60) +
159 (double) minutes * 60 + (double) seconds > Long.MAX_VALUE) {
160 throw new IllegalArgumentException("Duration seconds limit exceeded");
161 }
162 this.months = years * 12 + months;
163 long h = days * 24L + hours;
164 long m = h * 60L + minutes;
165 this.seconds = m * 60L + seconds;
166 this.nanoseconds = nanoseconds;
167 negative = someNegative;
168 normalizeZeroDuration();
169 typeLabel = type;
170 }
171
172
173 /**
174 * Ensure that a zero duration is considered positive
175 */
176
177 protected void normalizeZeroDuration() {
178 if (months == 0 && seconds == 0L && nanoseconds == 0) {
179 negative = false;
180 }
181 }
182
183 /**
184 * Static factory method: create a duration value from a supplied string, in
185 * ISO 8601 format [-]PnYnMnDTnHnMnS
186 *
187 * @param s a string in the lexical space of xs:duration
188 * @return the constructed xs:duration value, or a {@link ValidationFailure} if the
189 * supplied string is lexically invalid.
190 */
191
192 /*@NotNull*/
193 public static ConversionResult makeDuration(CharSequence s) {
194 return makeDuration(s, true, true);
195 }
196
197 /*@NotNull*/
198 protected static ConversionResult makeDuration(CharSequence s, boolean allowYM, boolean allowDT) {
199 int years = 0, months = 0, days = 0, hours = 0, minutes = 0, seconds = 0, nanoseconds = 0;
200 boolean negative = false;
201 StringTokenizer tok = new StringTokenizer(Whitespace.trimWhitespace(s).toString(), "-+.PYMDTHS", true);
202 int components = 0;
203 if (!tok.hasMoreElements()) {
204 return badDuration("empty string", s);
205 }
206 String part = (String) tok.nextElement();
207 if ("+".equals(part)) {
208 return badDuration("+ sign not allowed in a duration", s);
209 } else if ("-".equals(part)) {
210 negative = true;
211 part = (String) tok.nextElement();
212 }
213 if (!"P".equals(part)) {
214 return badDuration("missing 'P'", s);
215 }
216 int state = 0;
217 while (tok.hasMoreElements()) {
218 part = (String) tok.nextElement();
219 if ("T".equals(part)) {
220 state = 4;
221 if (!tok.hasMoreElements()) {
222 return badDuration("T must be followed by time components", s);
223 }
224 part = (String) tok.nextElement();
225 }
226 int value = simpleInteger(part);
227 if (value < 0) {
228 if (value == -2) {
229 return badDuration("component of duration exceeds Saxon limits", s, "FODT0002");
230 } else {
231 return badDuration("invalid or non-numeric component", s);
232 }
233 }
234 if (!tok.hasMoreElements()) {
235 return badDuration("missing unit letter at end", s);
236 }
237 char delim = ((String) tok.nextElement()).charAt(0);
238 switch (delim) {
239 case 'Y':
240 if (state > 0) {
241 return badDuration("Y is out of sequence", s);
242 }
243 if (!allowYM) {
244 return badDuration("Year component is not allowed in dayTimeDuration", s);
245 }
246 years = value;
247 state = 1;
248 components++;
249 break;
250 case 'M':
251 if (state == 4 || state == 5) {
252 if (!allowDT) {
253 return badDuration("Minute component is not allowed in yearMonthDuration", s);
254 }
255 minutes = value;
256 state = 6;
257 components++;
258 break;
259 } else if (state == 0 || state == 1) {
260 if (!allowYM) {
261 return badDuration("Month component is not allowed in dayTimeDuration", s);
262 }
263 months = value;
264 state = 2;
265 components++;
266 break;
267 } else {
268 return badDuration("M is out of sequence", s);
269 }
270 case 'D':
271 if (state > 2) {
272 return badDuration("D is out of sequence", s);
273 }
274 if (!allowDT) {
275 return badDuration("Day component is not allowed in yearMonthDuration", s);
276 }
277 days = value;
278 state = 3;
279 components++;
280 break;
281 case 'H':
282 if (state != 4) {
283 return badDuration("H is out of sequence", s);
284 }
285 if (!allowDT) {
286 return badDuration("Hour component is not allowed in yearMonthDuration", s);
287 }
288 hours = value;
289 state = 5;
290 components++;
291 break;
292 case '.':
293 if (state < 4 || state > 6) {
294 return badDuration("misplaced decimal point", s);
295 }
296 seconds = value;
297 state = 7;
298 break;
299 case 'S':
300 if (state < 4 || state > 7) {
301 return badDuration("S is out of sequence", s);
302 }
303 if (!allowDT) {
304 return badDuration("Seconds component is not allowed in yearMonthDuration", s);
305 }
306 if (state == 7) {
307 StringBuilder frac = new StringBuilder(part);
308 while (frac.length() < 9) {
309 frac.append("0");
310 }
311 part = frac.toString();
312 if (part.length() > 9) {
313 part = part.substring(0, 9);
314 }
315 value = simpleInteger(part);
316 if (value < 0) {
317 return badDuration("non-numeric fractional seconds", s);
318 }
319 nanoseconds = value;
320 } else {
321 seconds = value;
322 }
323 state = 8;
324 components++;
325 break;
326 default:
327 return badDuration("misplaced " + delim, s);
328 }
329 }
330
331 if (components == 0) {
332 return badDuration("Duration specifies no components", s);
333 }
334
335 if (negative) {
336 years = -years;
337 months = -months;
338 days = -days;
339 hours = -hours;
340 minutes = -minutes;
341 seconds = -seconds;
342 nanoseconds = -nanoseconds;
343 }
344
345 try {
346 return new DurationValue(
347 years, months, days, hours, minutes, seconds, nanoseconds, BuiltInAtomicType.DURATION);
348 } catch (IllegalArgumentException err) {
349 // catch values that exceed limits
350 return new ValidationFailure(err.getMessage());
351 }
352 }
353
354 protected static ValidationFailure badDuration(String msg, CharSequence s) {
355 ValidationFailure err = new ValidationFailure("Invalid duration value '" + s + "' (" + msg + ')');
356 err.setErrorCode("FORG0001");
357 return err;
358 }
359
360 protected static ValidationFailure badDuration(String msg, CharSequence s, String errorCode) {
361 ValidationFailure err = new ValidationFailure("Invalid duration value '" + s + "' (" + msg + ')');
362 err.setErrorCode(errorCode);
363 return err;
364 }
365
366 /**
367 * Parse a simple unsigned integer
368 *
369 * @param s the string containing the sequence of digits. No sign or whitespace is allowed.
370 * @return the integer. Return -1 if the string is not a sequence of digits, or -2 if it exceeds 2^31
371 */
372
373 protected static int simpleInteger(/*@NotNull*/ String s) {
374 long result = 0;
375 int len = s.length();
376 if (len == 0) {
377 return -1;
378 }
379 for (int i = 0; i < len; i++) {
380 char c = s.charAt(i);
381 if (c >= '0' && c <= '9') {
382 result = result * 10 + (c - '0');
383 if (result > Integer.MAX_VALUE) {
384 return -2;
385 }
386 } else {
387 return -1;
388 }
389 }
390 return (int) result;
391 }
392
393 /**
394 * Create a copy of this atomic value, with a different type label
395 *
396 * @param typeLabel the type label of the new copy. The caller is responsible for checking that
397 * the value actually conforms to this type.
398 */
399
400 public AtomicValue copyAsSubType(AtomicType typeLabel) {
401 if (negative) {
402 return new DurationValue(0, -months, 0, 0, 0, -seconds, -nanoseconds, typeLabel);
403 } else {
404 return new DurationValue(0, months, 0, 0, 0, seconds, nanoseconds, typeLabel);
405 }
406 }
407
408 /**
409 * Determine the primitive type of the value. This delivers the same answer as
410 * getItemType().getPrimitiveItemType(). The primitive types are
411 * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration,
412 * and xs:untypedAtomic. For external objects, the result is AnyAtomicType.
413 */
414
415 public BuiltInAtomicType getPrimitiveType() {
416 return BuiltInAtomicType.DURATION;
417 }
418
419 /**
420 * Return the signum of the value
421 *
422 * @return -1 if the duration is negative, zero if it is zero-length, +1 if it is positive
423 */
424
425 public int signum() {
426 if (negative) {
427 return -1;
428 }
429 if (months == 0 && seconds == 0L && nanoseconds == 0) {
430 return 0;
431 }
432 return +1;
433 }
434
435 /**
436 * Get the year component
437 *
438 * @return the number of years in the normalized duration; always positive
439 */
440
441 public int getYears() {
442 return months / 12;
443 }
444
445 /**
446 * Get the months component
447 *
448 * @return the number of months in the normalized duration; always positive, in the range 0-11
449 */
450
451 public int getMonths() {
452 return months % 12;
453 }
454
455 /**
456 * Get the days component
457 *
458 * @return the number of days in the normalized duration; always positive
459 */
460
461 public int getDays() {
462 // System.err.println("seconds = " + seconds);
463 // System.err.println("minutes = " + seconds / 60L);
464 // System.err.println("hours = " + seconds / (60L*60L));
465 // System.err.println("days = " + seconds / (24L*60L*60L));
466 // System.err.println("days (int) = " + (int)(seconds / (24L*60L*60L)));
467 return (int) (seconds / (24L * 60L * 60L));
468 }
469
470 /**
471 * Get the hours component
472 *
473 * @return the number of hours in the normalized duration; always positive, in the range 0-23
474 */
475
476 public int getHours() {
477 return (int) (seconds % (24L * 60L * 60L) / (60L * 60L));
478 }
479
480 /**
481 * Get the minutes component
482 *
483 * @return the number of minutes in the normalized duration; always positive, in the range 0-59
484 */
485
486 public int getMinutes() {
487 return (int) (seconds % (60L * 60L) / 60L);
488 }
489
490 /**
491 * Get the seconds component
492 *
493 * @return the number of whole seconds in the normalized duration; always positive, in the range 0-59
494 */
495
496 public int getSeconds() {
497 return (int) (seconds % 60L);
498 }
499
500 /**
501 * Get the microseconds component
502 *
503 * @return the number of nanoseconds in the normalized duration, divided by one thousand and rounded down;
504 * always positive, in the range 0-999999
505 */
506
507 public int getMicroseconds() {
508 return nanoseconds / 1000;
509 }
510
511 /**
512 * Get the nanoseconds component
513 *
514 * @return the number of nanoseconds in the normalized duration; always positive, in the range 0-999,999,999
515 */
516
517 public int getNanoseconds() {
518 return nanoseconds;
519 }
520
521 /**
522 * Get the total number of months (ignoring the days/hours/minutes/seconds)
523 *
524 * @return the total number of months, that is (getYears()*12) + getMonths(), as a positive
525 * or negative number according as the duration is positive or negative
526 */
527
528 public int getTotalMonths() {
529 return negative ? -months : months;
530 }
531
532 /**
533 * Get the total number of seconds (ignoring the years/months)
534 *
535 * @return the total number of seconds, as a positive
536 * or negative number according as the duration is positive or negative,
537 * with the fractional part indicating parts of a second to nanosecond precision
538 */
539
540 public BigDecimal getTotalSeconds() {
541 BigDecimal dec = new BigDecimal(negative ? -seconds : seconds);
542 if (nanoseconds != 0) {
543 dec = dec.add(new BigDecimal(BigInteger.valueOf(negative ? -nanoseconds : nanoseconds), 9));
544 }
545 return dec;
546 }
547
548 /**
549 * Convert to string
550 *
551 * @return ISO 8601 representation.
552 */
553
554 public CharSequence getPrimitiveStringValue() {
555
556 // Note, Schema does not define a canonical representation. We omit all zero components, unless
557 // the duration is zero-length, in which case we output PT0S.
558
559 if (months == 0 && seconds == 0L && nanoseconds == 0) {
560 return "PT0S";
561 }
562
563 FastStringBuffer sb = new FastStringBuffer(32);
564 if (negative) {
565 sb.append('-');
566 }
567 int years = getYears();
568 int months = getMonths();
569 int days = getDays();
570 int hours = getHours();
571 int minutes = getMinutes();
572 int seconds = getSeconds();
573
574 sb.append("P");
575 if (years != 0) {
576 sb.append(years + "Y");
577 }
578 if (months != 0) {
579 sb.append(months + "M");
580 }
581 if (days != 0) {
582 sb.append(days + "D");
583 }
584 if (hours != 0 || minutes != 0 || seconds != 0 || nanoseconds != 0) {
585 sb.append("T");
586 }
587 if (hours != 0) {
588 sb.append(hours + "H");
589 }
590 if (minutes != 0) {
591 sb.append(minutes + "M");
592 }
593 if (seconds != 0 || nanoseconds != 0) {
594 if (seconds != 0 && nanoseconds == 0) {
595 sb.append(seconds + "S");
596 } else {
597 long ms = (seconds * 1_000_000_000L) + nanoseconds;
598 String mss = ms + "";
599 if (seconds == 0) {
600 mss = "0000000000" + mss;
601 mss = mss.substring(mss.length() - 10);
602 }
603 sb.append(mss.substring(0, mss.length() - 9));
604 sb.append('.');
605 int lastSigDigit = mss.length() - 1;
606 while (mss.charAt(lastSigDigit) == '0') {
607 lastSigDigit--;
608 }
609 sb.append(mss.substring(mss.length() - 9, lastSigDigit + 1));
610 sb.append('S');
611 }
612 }
613
614 return sb;
615
616 }
617
618 /**
619 * Get length of duration in seconds, assuming an average length of month. (Note, this defines a total
620 * ordering on durations which is different from the partial order defined in XML Schema; XPath 2.0
621 * currently avoids defining an ordering at all. But the ordering here is consistent with the ordering
622 * of the two duration subtypes in XPath 2.0.)
623 *
624 * @return the duration in seconds, as a double
625 */
626
627 public double getLengthInSeconds() {
628 double a = months * (365.242199 / 12.0) * 24 * 60 * 60 + seconds + ((double) nanoseconds / 1_000_000_000);
629 return negative ? -a : a;
630 }
631
632 /**
633 * Get a component of the normalized value
634 * @param component the required component
635 */
636
637 public AtomicValue getComponent(AccessorFn.Component component) {
638 switch (component) {
639 case YEAR:
640 return Int64Value.makeIntegerValue(negative ? -getYears() : getYears());
641 case MONTH:
642 return Int64Value.makeIntegerValue(negative ? -getMonths() : getMonths());
643 case DAY:
644 return Int64Value.makeIntegerValue(negative ? -getDays() : getDays());
645 case HOURS:
646 return Int64Value.makeIntegerValue(negative ? -getHours() : getHours());
647 case MINUTES:
648 return Int64Value.makeIntegerValue(negative ? -getMinutes() : getMinutes());
649 case SECONDS:
650 FastStringBuffer sb = new FastStringBuffer(FastStringBuffer.C16);
651 String ms = "000000000" + nanoseconds;
652 ms = ms.substring(ms.length() - 9);
653 sb.append((negative ? "-" : "") + getSeconds() + '.' + ms);
654 return BigDecimalValue.parse(sb);
655 case WHOLE_SECONDS:
656 return Int64Value.makeIntegerValue(negative ? -seconds : seconds);
657 case MICROSECONDS:
658 return new Int64Value((negative ? -nanoseconds : nanoseconds) / 1000);
659 case NANOSECONDS:
660 return new Int64Value(negative ? -nanoseconds : nanoseconds);
661 default:
662 throw new IllegalArgumentException("Unknown component for duration: " + component);
663 }
664 }
665
666
667 /**
668 * Get an object value that implements the XPath equality and ordering comparison semantics for this value.
669 * If the ordered parameter is set to true, the result will be a Comparable and will support a compareTo()
670 * method with the semantics of the XPath lt/gt operator, provided that the other operand is also obtained
671 * using the getXPathComparable() method. In all cases the result will support equals() and hashCode() methods
672 * that support the semantics of the XPath eq operator, again provided that the other operand is also obtained
673 * using the getXPathComparable() method. A context argument is supplied for use in cases where the comparison
674 * semantics are context-sensitive, for example where they depend on the implicit timezone or the default
675 * collation.
676 *
677 * @param ordered true if an ordered comparison is required. In this case the result is null if the
678 * type is unordered; in other cases the returned value will be a Comparable.
679 * @param collator collation used for comparing string values
680 * @param implicitTimezone the XPath dynamic evaluation context, used in cases where the comparison is context
681 */
682
683 /*@Nullable*/
684 public AtomicMatchKey getXPathComparable(boolean ordered, StringCollator collator, int implicitTimezone) {
685 return ordered ? null : this;
686 }
687
688 /**
689 * Test if the two durations are of equal length.
690 *
691 * @throws ClassCastException if the other value is not an xs:duration or subtype thereof
692 */
693
694 public boolean equals(Object other) {
695 if (other instanceof DurationValue) {
696 DurationValue d1 = this;
697 DurationValue d2 = (DurationValue) other;
698
699 return d1.negative == d2.negative &&
700 d1.months == d2.months &&
701 d1.seconds == d2.seconds &&
702 d1.nanoseconds == d2.nanoseconds;
703 } else {
704 return false;
705 }
706 }
707
708 public int hashCode() {
709 return Double.valueOf(getLengthInSeconds()).hashCode();
710 }
711
712 /**
713 * Add two durations
714 *
715 * @param other the duration to be added to this one
716 * @return the sum of the two durations
717 */
718
719 public DurationValue add(DurationValue other) throws XPathException {
720 XPathException err = new XPathException("Only subtypes of xs:duration can be added");
721 err.setErrorCode("XPTY0004");
722 err.setIsTypeError(true);
723 throw err;
724 }
725
726 /**
727 * Subtract two durations
728 *
729 * @param other the duration to be subtracted from this one
730 * @return the difference of the two durations
731 */
732
733 public DurationValue subtract(DurationValue other) throws XPathException {
734 XPathException err = new XPathException("Only subtypes of xs:duration can be subtracted");
735 err.setErrorCode("XPTY0004");
736 err.setIsTypeError(true);
737 throw err;
738 }
739
740 /**
741 * Negate a duration (same as subtracting from zero, but it preserves the type of the original duration)
742 *
743 * @return the original duration with its sign reversed, retaining its type
744 */
745
746 public DurationValue negate() {
747 if (negative) {
748 return new DurationValue(0, months, 0, 0, 0, seconds, nanoseconds, typeLabel);
749 } else {
750 return new DurationValue(0, -months, 0, 0, 0, -seconds, -nanoseconds, typeLabel);
751 }
752 }
753
754 /**
755 * Multiply a duration by an integer
756 *
757 * @param factor the number to multiply by
758 * @return the result of the multiplication
759 */
760
761 public DurationValue multiply(long factor) throws XPathException {
762 return multiply((double)factor);
763 }
764
765
766 /**
767 * Multiply a duration by a number
768 *
769 * @param factor the number to multiply by
770 * @return the result of the multiplication
771 */
772
773 public DurationValue multiply(double factor) throws XPathException {
774 XPathException err = new XPathException("Only subtypes of xs:duration can be multiplied by a number");
775 err.setErrorCode("XPTY0004");
776 err.setIsTypeError(true);
777 throw err;
778 }
779
780 /**
781 * Divide a duration by a number
782 *
783 * @param factor the number to divide by
784 * @return the result of the division
785 */
786
787 public DurationValue divide(double factor) throws XPathException {
788 XPathException err = new XPathException("Only subtypes of xs:duration can be divided by a number");
789 err.setErrorCode("XPTY0004");
790 err.setIsTypeError(true);
791 throw err;
792 }
793
794 /**
795 * Divide a duration by a another duration
796 *
797 * @param other the duration to divide by
798 * @return the result of the division
799 */
800
801 public BigDecimalValue divide(DurationValue other) throws XPathException {
802 XPathException err = new XPathException("Only subtypes of xs:duration can be divided by another duration");
803 err.setErrorCode("XPTY0004");
804 err.setIsTypeError(true);
805 throw err;
806 }
807
808 /**
809 * Get a Comparable value that implements the XML Schema ordering comparison semantics for this value.
810 * This implementation handles the ordering rules for durations in XML Schema.
811 * It is overridden for the two subtypes DayTimeDuration and YearMonthDuration.
812 *
813 * @return a suitable Comparable
814 */
815
816 /*@NotNull*/
817 public Comparable getSchemaComparable() {
818 return getSchemaComparable(this);
819 }
820
821 /**
822 * Get a Comparable value that implements the XML Schema ordering comparison semantics for this value.
823 * This implementation handles the ordering rules for durations in XML Schema.
824 *
825 * @param value the duration for which a comparison key is required
826 * @return a suitable Comparable
827 */
828
829 /*@NotNull*/
830 public static Comparable getSchemaComparable(/*@NotNull*/ DurationValue value) {
831 int m = value.months;
832 long s = value.seconds;
833 int n = value.nanoseconds;
834 if (value.negative) {
835 s = -s;
836 m = -m;
837 n = -n;
838 }
839 return new DurationComparable(m, s, n);
840 }
841
842 /**
843 * DurationValueOrderingKey is a Comparable value that acts as a surrogate for a Duration,
844 * having ordering rules that implement the XML Schema specification.
845 */
846
847 private static class DurationComparable implements Comparable<DurationComparable> {
848
849 private int months;
850 private long seconds;
851 private int nanoseconds;
852
853 public DurationComparable(int m, long s, int nanos) {
854 months = m;
855 seconds = s;
856 nanoseconds = nanos;
857 }
858
859 /**
860 * Compare two durations according to the XML Schema rules.
861 *
862 * @param other the other duration
863 * @return -1 if this duration is smaller; 0 if they are equal; +1 if this duration is greater;
864 * {@link net.sf.saxon.om.SequenceTool#INDETERMINATE_ORDERING} if there is no defined order
865 */
866
867 public int compareTo(DurationComparable other) {
868 //DurationComparable other = ;
869 // if (o instanceof DurationComparable) {
870 // other = (DurationComparable) o;
871 // } else if (o instanceof YearMonthDurationValue) {
872 // other = (DurationComparable) getSchemaComparable((YearMonthDurationValue) o);
873 // } else if (o instanceof DayTimeDurationValue) {
874 // other = (DurationComparable) getSchemaComparable((DayTimeDurationValue) o);
875 // } else {
876 // return SequenceTool.INDETERMINATE_ORDERING;
877 // }
878 if (months == other.months) {
879 if (seconds == other.seconds) {
880 return Integer.compare(nanoseconds, other.nanoseconds);
881 } else {
882 return Long.compare(seconds, other.seconds);
883 }
884 } else {
885 // The months figure varies, but the seconds figure might tip things over if it's high
886 // enough. We make the assumption, however, that the nanoseconds won't affect things.
887 double oneDay = 24e0 * 60e0 * 60e0;
888 double min0 = monthsToDaysMinimum(months) * oneDay + seconds;
889 double max0 = monthsToDaysMaximum(months) * oneDay + seconds;
890 double min1 = monthsToDaysMinimum(other.months) * oneDay + other.seconds;
891 double max1 = monthsToDaysMaximum(other.months) * oneDay + other.seconds;
892 if (max0 < min1) {
893 return -1;
894 } else if (min0 > max1) {
895 return +1;
896 } else {
897 return SequenceTool.INDETERMINATE_ORDERING;
898 }
899 }
900 }
901
902 public boolean equals(Object o) {
903 return o instanceof DurationComparable && compareTo((DurationComparable)o) == 0;
904 }
905
906 public int hashCode() {
907 return months ^ (int) seconds;
908 }
909
910 private int monthsToDaysMinimum(int months) {
911 if (months < 0) {
912 return -monthsToDaysMaximum(-months);
913 }
914 if (months < 12) {
915 int[] shortest = {0, 28, 59, 89, 120, 150, 181, 212, 242, 273, 303, 334};
916 return shortest[months];
917 } else {
918 int years = months / 12;
919 int remainingMonths = months % 12;
920 // the -1 is to allow for the fact that we might miss a leap day if we time the start badly
921 int yearDays = years * 365 + (years % 4) - (years % 100) + (years % 400) - 1;
922 return yearDays + monthsToDaysMinimum(remainingMonths);
923 }
924 }
925
926 private int monthsToDaysMaximum(int months) {
927 if (months < 0) {
928 return -monthsToDaysMinimum(-months);
929 }
930 if (months < 12) {
931 int[] longest = {0, 31, 62, 92, 123, 153, 184, 215, 245, 276, 306, 337};
932 return longest[months];
933 } else {
934 int years = months / 12;
935 int remainingMonths = months % 12;
936 // the +1 is to allow for the fact that we might miss a leap day if we time the start badly
937 int yearDays = years * 365 + (years % 4) - (years % 100) + (years % 400) + 1;
938 return yearDays + monthsToDaysMaximum(remainingMonths);
939 }
940 }
941 }
942
943 }
944