Debian Codegraph @

net/sf/saxon/value/YearMonthDurationValue.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.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.RoundingMode;
21
22 /**
23 * A value of type xs:yearMonthDuration.
24 * <p>The state retained by this class is essentially a signed 32-bit integer representing the number
25 * of months: that is, {@code year*12 + month}; plus a type label allowing subtypes of {@code xs:yearMonthDuration}
26 * to be represented.</p>
27 */
28
29 public final class YearMonthDurationValue extends DurationValue implements Comparable<YearMonthDurationValue> {
30
31 /**
32 * Private constructor for internal use
33 */
34
35 private YearMonthDurationValue() {
36 typeLabel = BuiltInAtomicType.YEAR_MONTH_DURATION;
37 }
38
39 /**
40 * Static factory: create a year-month duration value from a supplied string, in
41 * ISO 8601 format [+|-]PnYnM
42 *
43 * @param s a string in the lexical space of xs:yearMonthDuration.
44 * @return either a YearMonthDurationValue, or a ValidationFailure if the string was
45 * not in the lexical space of xs:yearMonthDuration.
46 */
47
48 public static ConversionResult makeYearMonthDurationValue(CharSequence s) {
49 ConversionResult d = DurationValue.makeDuration(s, true, false);
50 if (d instanceof ValidationFailure) {
51 return d;
52 }
53 DurationValue dv = (DurationValue) d;
54 return YearMonthDurationValue.fromMonths((dv.getYears() * 12 + dv.getMonths()) * dv.signum());
55 }
56
57 /**
58 * Create a copy of this atomic value, with a different type label
59 *
60 * @param typeLabel the type label of the new copy. The caller is responsible for checking that
61 * the value actually conforms to this type.
62 */
63
64 /*@NotNull*/
65 public AtomicValue copyAsSubType(AtomicType typeLabel) {
66 YearMonthDurationValue v = YearMonthDurationValue.fromMonths(getLengthInMonths());
67 v.typeLabel = typeLabel;
68 return v;
69 }
70
71 /**
72 * Determine the primitive type of the value. This delivers the same answer as
73 * getItemType().getPrimitiveItemType(). The primitive types are
74 * the 19 primitive types of XML Schema, plus xs:integer, xs:dayTimeDuration and xs:yearMonthDuration,
75 * and xs:untypedAtomic. For external objects, the result is AnyAtomicType.
76 */
77
78 public BuiltInAtomicType getPrimitiveType() {
79 return BuiltInAtomicType.YEAR_MONTH_DURATION;
80 }
81
82 /**
83 * Convert to string
84 *
85 * @return ISO 8601 representation.
86 */
87
88 public CharSequence getPrimitiveStringValue() {
89
90 // The canonical representation has months in the range 0-11
91
92 int y = getYears();
93 int m = getMonths();
94
95 FastStringBuffer sb = new FastStringBuffer(32);
96 if (negative) {
97 sb.append('-');
98 }
99 sb.append('P');
100 if (y != 0) {
101 sb.append(y + "Y");
102 }
103 if (m != 0 || y == 0) {
104 sb.append(m + "M");
105 }
106 return sb;
107
108 }
109
110 /**
111 * Get the number of months in the duration
112 *
113 * @return the number of months in the duration
114 */
115
116 public int getLengthInMonths() {
117 return months * (negative ? -1 : +1);
118 }
119
120 /**
121 * Construct a duration value as a number of months.
122 *
123 * @param months the number of months (may be negative)
124 * @return the corresponding xs:yearMonthDuration value
125 */
126
127 public static YearMonthDurationValue fromMonths(int months) {
128 YearMonthDurationValue mdv = new YearMonthDurationValue();
129 mdv.negative = months < 0;
130 mdv.months = months < 0 ? -months : months;
131 mdv.seconds = 0;
132 mdv.nanoseconds = 0;
133 return mdv;
134 }
135
136 /**
137 * Multiply a duration by an integer
138 *
139 * @param factor the number to multiply by
140 * @return the result of the multiplication
141 */
142
143 public YearMonthDurationValue multiply(long factor) throws XPathException {
144 // Fast path for simple cases
145 if (Math.abs(factor) < 30_000 && Math.abs(months) < 30_000) {
146 return YearMonthDurationValue.fromMonths((int)factor * getLengthInMonths());
147 } else {
148 return multiply((double)factor);
149 }
150 }
151
152 /**
153 * Multiply duration by a number.
154 */
155
156 public YearMonthDurationValue multiply(double n) throws XPathException {
157 if (Double.isNaN(n)) {
158 XPathException err = new XPathException("Cannot multiply a duration by NaN");
159 err.setErrorCode("FOCA0005");
160 throw err;
161 }
162 double m = (double) getLengthInMonths();
163 double product = n * m;
164 if (Double.isInfinite(product) || product > Integer.MAX_VALUE || product < Integer.MIN_VALUE) {
165 XPathException err = new XPathException("Overflow when multiplying a duration by a number");
166 err.setErrorCode("FODT0002");
167 throw err;
168 }
169 return fromMonths((int) Math.round(product));
170 }
171
172
173 /**
174 * Divide duration by a number.
175 */
176
177 public DurationValue divide(double n) throws XPathException {
178 if (Double.isNaN(n)) {
179 XPathException err = new XPathException("Cannot divide a duration by NaN");
180 err.setErrorCode("FOCA0005");
181 throw err;
182 }
183 double m = (double) getLengthInMonths();
184 double product = m / n;
185 if (Double.isInfinite(product) || product > Integer.MAX_VALUE || product < Integer.MIN_VALUE) {
186 XPathException err = new XPathException("Overflow when dividing a duration by a number");
187 err.setErrorCode("FODT0002");
188 throw err;
189 }
190 return fromMonths((int) Math.round(product));
191 }
192
193 /**
194 * Find the ratio between two durations
195 *
196 * @param other the dividend
197 * @return the ratio, as a decimal
198 * @throws XPathException if an error occurs, for example division by zero or dividing durations of different type
199 */
200
201 public BigDecimalValue divide(DurationValue other) throws XPathException {
202 if (other instanceof YearMonthDurationValue) {
203 BigDecimal v1 = BigDecimal.valueOf(getLengthInMonths());
204 BigDecimal v2 = BigDecimal.valueOf(((YearMonthDurationValue) other).getLengthInMonths());
205 if (v2.signum() == 0) {
206 XPathException err = new XPathException("Divide by zero (durations)");
207 err.setErrorCode("FOAR0001");
208 throw err;
209 }
210 return new BigDecimalValue(v1.divide(v2, 20, RoundingMode.HALF_EVEN));
211 } else {
212 XPathException err = new XPathException("Cannot divide two durations of different type");
213 err.setErrorCode("XPTY0004");
214 throw err;
215 }
216 }
217
218 /**
219 * Add two year-month-durations
220 */
221
222 public DurationValue add(DurationValue other) throws XPathException {
223 if (other instanceof YearMonthDurationValue) {
224 return fromMonths(getLengthInMonths() +
225 ((YearMonthDurationValue) other).getLengthInMonths());
226 } else {
227 XPathException err = new XPathException("Cannot add two durations of different type");
228 err.setErrorCode("XPTY0004");
229 throw err;
230 }
231 }
232
233 /**
234 * Subtract two year-month-durations
235 */
236
237 public DurationValue subtract(DurationValue other) throws XPathException {
238 if (other instanceof YearMonthDurationValue) {
239 return fromMonths(getLengthInMonths() -
240 ((YearMonthDurationValue) other).getLengthInMonths());
241 } else {
242 XPathException err = new XPathException("Cannot subtract two durations of different type");
243 err.setErrorCode("XPTY0004");
244 throw err;
245 }
246 }
247
248 /**
249 * Negate a duration (same as subtracting from zero, but it preserves the type of the original duration)
250 */
251
252 public DurationValue negate() {
253 return fromMonths(-getLengthInMonths());
254 }
255
256 /**
257 * Compare the value to another duration value
258 *
259 * @param other The other dateTime value
260 * @return negative value if this one is the earler, 0 if they are chronologically equal,
261 * positive value if this one is the later. For this purpose, dateTime values with an unknown
262 * timezone are considered to be UTC values (the Comparable interface requires
263 * a total ordering).
264 * @throws ClassCastException if the other value is not a DateTimeValue (the parameter
265 * is declared as Object to satisfy the Comparable interface)
266 */
267
268 public int compareTo(YearMonthDurationValue other) {
269 return Integer.compare(getLengthInMonths(), other.getLengthInMonths());
270 }
271
272 /**
273 * Get a Comparable value that implements the XPath ordering comparison semantics for this value.
274 * Returns null if the value is not comparable according to XPath rules. The default implementation
275 * returns the value itself. This is modified for types such as
276 * xs:duration which allow ordering comparisons in XML Schema, but not in XPath.
277 *
278 * @param ordered true if ordered comparisons need to be supported
279 * @param collator for comparing strings - not used
280 * @param implicitTimezone implicit timezone in the dynamic context - not used
281 */
282
283 public AtomicMatchKey getXPathComparable(boolean ordered, StringCollator collator, int implicitTimezone) {
284 return this;
285 }
286
287
288 }
289