Duration.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. package gnu.math;
  2. import java.io.*;
  3. public class Duration extends Quantity implements Externalizable
  4. {
  5. public Unit unit;
  6. /** Number of whole months. May be negative. */
  7. int months;
  8. /** Does not include any leap seconds.
  9. * I.e. @code{sign * ((24 * days + hours) * 60 + minutes) * 60 + seconds},
  10. * where {@code hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60
  11. * && secconds >= 0 && minutes > 60}.
  12. */
  13. long seconds;
  14. /** Number of nanoseconds.
  15. * We could possibly include leap seconds in here. */
  16. int nanos;
  17. public static Duration make (int months, long seconds, int nanos, Unit unit)
  18. {
  19. Duration d = new Duration();
  20. d.months = months;
  21. d.seconds = seconds;
  22. d.nanos = nanos;
  23. d.unit = unit;
  24. return d;
  25. }
  26. public static Duration makeMonths(int months)
  27. {
  28. Duration d = new Duration();
  29. d.unit = Unit.month;
  30. d.months = months;
  31. return d;
  32. }
  33. public static Duration makeMinutes (int minutes)
  34. {
  35. Duration d = new Duration();
  36. d.unit = Unit.second;
  37. d.seconds = 60 * minutes;
  38. return d;
  39. }
  40. public static Duration parse (String str, Unit unit)
  41. {
  42. Duration d = Duration.valueOf(str, unit);
  43. if (d == null)
  44. throw new IllegalArgumentException("not a valid "+unit.getName()+" duration: '"+str+"'");
  45. return d;
  46. }
  47. public static Duration parseDuration (String str)
  48. {
  49. return parse(str, Unit.duration);
  50. }
  51. public static Duration parseYearMonthDuration (String str)
  52. {
  53. return parse(str, Unit.month);
  54. }
  55. public static Duration parseDayTimeDuration (String str)
  56. {
  57. return parse(str, Unit.second);
  58. }
  59. /** Parse a duration lexical value as specified by XML Schama.
  60. * Return null if invalid syntax.
  61. */
  62. public static Duration valueOf (String str, Unit unit)
  63. {
  64. str = str.trim();
  65. int pos = 0;
  66. int len = str.length();
  67. boolean negative;
  68. if (pos < len && str.charAt(pos) == '-')
  69. {
  70. negative = true;
  71. pos++;
  72. }
  73. else
  74. negative = false;
  75. if (pos + 1 >= len || str.charAt(pos) != 'P')
  76. return null;
  77. pos++;
  78. int months = 0, nanos = 0;
  79. long seconds = 0;
  80. long part = scanPart(str, pos);
  81. pos = ((int) part) >> 16;
  82. char ch = (char) part;
  83. if (unit == Unit.second && (ch == 'Y' || ch == 'M'))
  84. return null;
  85. if (ch == 'Y')
  86. {
  87. months = 12 * (int) (part >> 32);
  88. pos = ((int) part) >> 16;
  89. part = scanPart(str, pos);
  90. ch = (char) part;
  91. }
  92. if (ch == 'M')
  93. {
  94. months += (part >> 32);
  95. pos = ((int) part) >> 16;
  96. part = scanPart(str, pos);
  97. ch = (char) part;
  98. }
  99. if (unit == Unit.month && pos != len)
  100. return null;
  101. if (ch == 'D')
  102. {
  103. if (unit == Unit.month)
  104. return null;
  105. seconds = (long) (24 * 60 * 60) * (int) (part >> 32);
  106. pos = ((int) part) >> 16;
  107. part = scanPart (str, pos);
  108. }
  109. if (part != (pos << 16))
  110. return null;
  111. if (pos == len)
  112. {
  113. // No time part
  114. }
  115. else if (str.charAt(pos) != 'T' || ++pos == len)
  116. return null;
  117. else // saw 'T'
  118. {
  119. if (unit == Unit.month)
  120. return null;
  121. part = scanPart (str, pos);
  122. ch = (char) part;
  123. if (ch == 'H')
  124. {
  125. seconds += (60 * 60) * (int) (part >> 32);
  126. pos = ((int) part) >> 16;
  127. part = scanPart (str, pos);
  128. ch = (char) part;
  129. }
  130. if (ch == 'M')
  131. {
  132. seconds += 60 * (int) (part >> 32);
  133. pos = ((int) part) >> 16;
  134. part = scanPart (str, pos);
  135. ch = (char) part;
  136. }
  137. if (ch == 'S' || ch == '.')
  138. {
  139. seconds += (int) (part >> 32);
  140. pos = ((int) part) >> 16;
  141. }
  142. if (ch == '.' && pos + 1 < len
  143. && Character.digit(str.charAt(pos), 10) >= 0)
  144. {
  145. int nfrac = 0;
  146. for (; pos < len; nfrac++)
  147. {
  148. ch = str.charAt(pos++);
  149. int dig = Character.digit(ch, 10);
  150. if (dig < 0)
  151. break;
  152. if (nfrac < 9)
  153. nanos = 10 * nanos + dig;
  154. else if (nfrac == 9 && dig >= 5)
  155. nanos++;
  156. }
  157. while (nfrac++ < 9)
  158. nanos = 10 * nanos;
  159. if (ch != 'S')
  160. return null;
  161. }
  162. }
  163. if (pos != len)
  164. return null;
  165. Duration d = new Duration();
  166. if (negative)
  167. {
  168. months = -months;
  169. seconds = -seconds;
  170. nanos = -nanos;
  171. }
  172. d.months = months;
  173. d.seconds = seconds;
  174. d.nanos = nanos;
  175. d.unit = unit;
  176. return d;
  177. }
  178. public Numeric add (Object y, int k)
  179. {
  180. if (y instanceof Duration)
  181. return Duration.add (this, (Duration) y, k);
  182. if (y instanceof DateTime && k == 1)
  183. return DateTime.add((DateTime) y, this, 1);
  184. throw new IllegalArgumentException ();
  185. }
  186. public Numeric mul (Object y)
  187. {
  188. if (y instanceof RealNum)
  189. return Duration.times(this, ((RealNum) y).doubleValue());
  190. return ((Numeric)y).mulReversed (this);
  191. }
  192. public Numeric mulReversed (Numeric x)
  193. {
  194. if (! (x instanceof RealNum))
  195. throw new IllegalArgumentException ();
  196. return Duration.times(this, ((RealNum) x).doubleValue());
  197. }
  198. public static double div (Duration dur1, Duration dur2)
  199. {
  200. int months1 = dur1.months;
  201. int months2 = dur2.months;
  202. double sec1 = (double) dur1.seconds + dur1.nanos * 0.000000001;
  203. double sec2 = (double) dur2.seconds + dur1.nanos * 0.000000001;
  204. if (months2 == 0 && sec2 == 0)
  205. throw new ArithmeticException("divide duration by zero");
  206. if (months2 == 0)
  207. {
  208. if (months1 == 0)
  209. return sec1 /sec2;
  210. }
  211. else if (sec2 == 0)
  212. {
  213. if (sec1 == 0)
  214. return (double) months1 / (double) months2;
  215. }
  216. throw new ArithmeticException("divide of incompatible durations");
  217. }
  218. public Numeric div (Object y)
  219. {
  220. if (y instanceof RealNum)
  221. {
  222. double dy = ((RealNum) y).doubleValue();
  223. if (dy == 0 || Double.isNaN(dy))
  224. throw new ArithmeticException("divide of duration by 0 or NaN");
  225. return Duration.times(this, 1.0 / dy);
  226. }
  227. if (y instanceof Duration)
  228. return new DFloNum(div(this, (Duration) y));
  229. return ((Numeric)y).divReversed (this);
  230. }
  231. public static Duration add (Duration x, Duration y, int k)
  232. {
  233. long months = (long) x.months + k * (long) y.months;
  234. // FIXME does not handle leap-seconds represented as multiples of
  235. // 10^9 in the nanos field.
  236. long nanos = x.seconds * 1000000000L + (long) x.nanos
  237. + k * (y.seconds * 1000000000L + y.nanos);
  238. // FIXME check for overflow
  239. // FIXME handle inconsistent signs.
  240. Duration d = new Duration();
  241. d.months = (int) months;
  242. d.seconds = (int) (nanos / 1000000000L);
  243. d.nanos = (int) (nanos % 1000000000L);
  244. if (x.unit != y.unit || x.unit == Unit.duration)
  245. throw new ArithmeticException("cannot add these duration types");
  246. d.unit = x.unit;
  247. return d;
  248. }
  249. public static Duration times (Duration x, double y)
  250. {
  251. if (x.unit == Unit.duration)
  252. throw new IllegalArgumentException("cannot multiply general duration");
  253. double months = x.months * y;
  254. if (Double.isInfinite(months) || Double.isNaN(months))
  255. throw new ArithmeticException("overflow/NaN when multiplying a duration");
  256. double nanos = (x.seconds * 1000000000L + x.nanos) * y;
  257. Duration d = new Duration();
  258. d.months = (int) Math.floor(months + 0.5);
  259. d.seconds = (int) (nanos / 1000000000L);
  260. d.nanos = (int) (nanos % 1000000000L);
  261. d.unit = x.unit;
  262. return d;
  263. }
  264. public static int compare (Duration x, Duration y)
  265. {
  266. long months = (long) x.months - (long) y.months;
  267. long nanos = x.seconds * 1000000000L + (long) x.nanos
  268. - (y.seconds * 1000000000L + y.nanos);
  269. if (months < 0 && nanos <= 0)
  270. return -1;
  271. if (months > 0 && nanos >= 0)
  272. return 1;
  273. if (months == 0)
  274. return nanos < 0 ? -1 : nanos > 0 ? 1 : 0;
  275. return -2;
  276. }
  277. public int compare (Object obj)
  278. {
  279. if (obj instanceof Duration)
  280. return compare(this, (Duration) obj);
  281. // Could also compare other Quanties if units match appropriately. FIXME.
  282. throw new IllegalArgumentException ();
  283. }
  284. public String toString ()
  285. {
  286. StringBuffer sbuf = new StringBuffer();
  287. int m = months;
  288. long s = seconds;
  289. int n = nanos;
  290. boolean neg = m < 0 || s < 0 || n < 0;
  291. if (neg)
  292. {
  293. m = -m;
  294. s = -s;
  295. n = -n;
  296. sbuf.append('-');
  297. }
  298. sbuf.append('P');
  299. int y = m / 12;
  300. if (y != 0)
  301. {
  302. sbuf.append(y);
  303. sbuf.append('Y');
  304. m -= y * 12;
  305. }
  306. if (m != 0)
  307. {
  308. sbuf.append(m);
  309. sbuf.append('M');
  310. }
  311. long d = s / (24 * 60 * 60);
  312. if (d != 0)
  313. {
  314. sbuf.append(d);
  315. sbuf.append('D');
  316. s -= 24 * 60 * 60 * d;
  317. }
  318. if (s != 0 || n != 0)
  319. {
  320. sbuf.append('T');
  321. long hr = s / (60 * 60);
  322. if (hr != 0)
  323. {
  324. sbuf.append(hr);
  325. sbuf.append('H');
  326. s -= 60 * 60 * hr;
  327. }
  328. long mn = s / 60;
  329. if (mn != 0)
  330. {
  331. sbuf.append(mn);
  332. sbuf.append('M');
  333. s -= 60 * mn;
  334. }
  335. if (s != 0 || n != 0)
  336. {
  337. sbuf.append(s);
  338. appendNanoSeconds(n, sbuf);
  339. sbuf.append('S');
  340. }
  341. }
  342. else if (sbuf.length() == 1)
  343. sbuf.append(unit == Unit.month ? "0M" : "T0S");
  344. return sbuf.toString();
  345. }
  346. static void appendNanoSeconds (int nanoSeconds, StringBuffer sbuf)
  347. {
  348. if (nanoSeconds == 0)
  349. return;
  350. sbuf.append('.');
  351. int pos = sbuf.length();
  352. sbuf.append(nanoSeconds);
  353. int len = sbuf.length();
  354. int pad = pos + 9 - len;
  355. while (--pad >= 0)
  356. sbuf.insert(pos, '0');
  357. len = pos + 9;
  358. do { --len; } while (sbuf.charAt(len) == '0');
  359. sbuf.setLength(len+1);
  360. }
  361. /** Parse digits following by a terminator char
  362. * @return {@code (VALUE << 32)|(FOLLOWING_POS<<16)|FOLLOWING_CHAR}.
  363. * If there are no digits return @code{START<<16}.
  364. * Otherwise, on overflow or digits followed by end-of-string, return -1.
  365. */
  366. private static long scanPart (String str, int start)
  367. {
  368. int i = start;
  369. long val = -1;
  370. int len = str.length();
  371. while (i < len)
  372. {
  373. char ch = str.charAt(i);
  374. i++;
  375. int dig = Character.digit(ch, 10);
  376. if (dig < 0)
  377. {
  378. if (val < 0) return start << 16;
  379. return (val << 32) | (i << 16) | ((int) ch);
  380. }
  381. val = val < 0 ? dig : 10 * val + dig;
  382. if (val > Integer.MAX_VALUE)
  383. return -1; // overflow
  384. }
  385. return val < 0 ? (start << 16) : -1;
  386. }
  387. /** The number of years in the canonical representation. */
  388. public int getYears ()
  389. {
  390. return months / 12;
  391. }
  392. public int getMonths()
  393. {
  394. return months % 12;
  395. }
  396. public int getDays ()
  397. {
  398. return (int) (seconds / (24 * 60 * 60));
  399. }
  400. public int getHours ()
  401. {
  402. return (int) ((seconds / (60 * 60)) % 24);
  403. }
  404. public int getMinutes ()
  405. {
  406. return (int) ((seconds / 60) % 60);
  407. }
  408. public int getSecondsOnly ()
  409. {
  410. return (int) (seconds % 60);
  411. }
  412. public int getNanoSecondsOnly ()
  413. {
  414. return nanos;
  415. }
  416. public int getTotalMonths ()
  417. {
  418. return months;
  419. }
  420. public long getTotalSeconds ()
  421. {
  422. return seconds;
  423. }
  424. public long getTotalMinutes ()
  425. {
  426. return seconds / 60;
  427. }
  428. public long getNanoSeconds ()
  429. {
  430. return seconds * 1000000000L + nanos;
  431. }
  432. public boolean isZero ()
  433. {
  434. return months == 0 && seconds == 0 && nanos == 0;
  435. }
  436. public boolean isExact ()
  437. {
  438. return false;
  439. }
  440. public void writeExternal(ObjectOutput out) throws IOException
  441. {
  442. out.writeInt(months);
  443. out.writeLong(seconds);
  444. out.writeInt(nanos);
  445. out.writeObject(unit);
  446. }
  447. public void readExternal(ObjectInput in)
  448. throws IOException, ClassNotFoundException
  449. {
  450. months = in.readInt();
  451. seconds = in.readLong();
  452. nanos = in.readInt();
  453. unit = (Unit) in.readObject();
  454. }
  455. public Unit unit() { return unit; }
  456. public Complex number ()
  457. {
  458. throw new UnsupportedOperationException("number needs to be implemented!");
  459. }
  460. public int hashCode ()
  461. {
  462. return months ^ (int) seconds ^ nanos;
  463. }
  464. /** Compare for equality.
  465. * Ignores unit.
  466. */
  467. public static boolean equals (Duration x, Duration y)
  468. {
  469. return x.months == y.months
  470. && x.seconds == y.seconds
  471. && x.nanos == y.nanos;
  472. }
  473. /** Compare for equality.
  474. * Ignores unit.
  475. */
  476. public boolean equals (Object obj)
  477. {
  478. if (obj == null || ! (obj instanceof Duration))
  479. return false;
  480. return Duration.equals (this, (Duration) obj);
  481. }
  482. }