Debian Codegraph @

terps/tads/tads3/vmdate.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header$";
4 #endif
5
6 /*
7 * Copyright (c) 2012 Michael J. Roberts. All Rights Reserved.
8 *
9 * Please see the accompanying license file, LICENSE.TXT, for information
10 * on using and copying this software.
11 */
12 /*
13 Name
14 vmdate.cpp - CVmObjDate object
15 Function
16 Implements the Date intrinsic class
17 Notes
18
19 Modified
20 01/23/12 MJRoberts - Creation
21 */
22
23 #include <stdlib.h>
24 #include <string.h>
25 #include <assert.h>
26 #include <time.h>
27 #include <math.h>
28 #include <ctype.h>
29 #include <limits.h>
30 #include <stdarg.h>
31
32 #include "t3std.h"
33 #include "vmdate.h"
34 #include "vmerr.h"
35 #include "vmerrnum.h"
36 #include "vmtype.h"
37 #include "vmglob.h"
38 #include "vmobj.h"
39 #include "vmundo.h"
40 #include "vmmcreg.h"
41 #include "vmfile.h"
42 #include "vmbignum.h"
43 #include "vmbif.h"
44 #include "vmmeta.h"
45 #include "vmstack.h"
46 #include "vmrun.h"
47 #include "vmstr.h"
48 #include "vmlst.h"
49 #include "vmvec.h"
50 #include "vmlookup.h"
51 #include "utf8.h"
52 #include "vmuni.h"
53 #include "vmtz.h"
54 #include "vmtzobj.h"
55
56
57 /* ------------------------------------------------------------------------ */
58 /*
59 * Round a double to int32
60 */
61 static int32_t round_int32(double d)
62 {
63 double i;
64 return (int32_t)(modf(d, &i) >= 0.5
65 ? (d >= 0 ? ceil(d) : floor(d))
66 : (d < 0 ? ceil(d) : floor(d)));
67 }
68
69
70 /* ------------------------------------------------------------------------ */
71 /*
72 * get the current date/time in UTC
73 */
74 void caldate_t::now(int32_t &dayno, int32_t &daytime)
75 {
76 /* get the current date and time in Unix Epoch format */
77 os_time_t s;
78 long ns;
79 os_time_ns(&s, &ns);
80
81 /*
82 * 's' is the number of seconds since the Unix Epoch, 1/1/1970 UTC.
83 * Get our day number: divide by seconds per day to get days past the
84 * Unix Epoch, then adjust to our Epoch (3/1/0000 UTC) by adding the
85 * number of days from our Epoch to the Unix Epoch.
86 */
87 dayno = (int32_t)(s/(24*60*60) + caldate_t::UNIX_EPOCH_DAYNO);
88
89 /*
90 * convert 's' to the time of day, adding in the fractional portion
91 * from 'ns' but only keeping millisecond precision
92 */
93 daytime = (uint32_t)((s % (24*60*60))*1000 + ns/1000000);
94 }
95
96
97 /*
98 * normalize a date/time value: if the daytime value is before 0000 hours
99 * or after 2400 hours, bring it back within bounds and adjust the day
100 * number
101 */
102 void caldate_t::normalize(int32_t &dayno, int32_t &daytime)
103 {
104 /* if we're outside the 0000-2400 bounds, adjust the time and day */
105 ldiv_t q = ldiv(daytime, 24*60*60*1000);
106 dayno += (int32_t)q.quot;
107 if ((daytime = (int32_t)q.rem) < 0)
108 {
109 daytime += 24*60*60*1000;
110 dayno -= 1;
111 }
112 }
113
114 /* ------------------------------------------------------------------------ */
115 /*
116 * Locale string retrieval
117 */
118 class CVmDateLocale
119 {
120 public:
121 CVmDateLocale(VMG0_)
122 {
123 /* get the state Vector from the Date static class state holder */
124 const vm_val_t *val = vm_classobj_for(CVmObjDate)->get_class_state();
125 vecid = val->typ == VM_OBJ ? val->val.obj : VM_INVALID_OBJ;
126 vec = vm_objid_cast(CVmObjVector, vecid);
127 }
128
129 /* get a locale string */
130 const char *get(VMG_ size_t &len, int idx)
131 {
132 /* if it's negative, it's invalid */
133 if (idx < 0)
134 {
135 len = 0;
136 return 0;
137 }
138
139 /* try getting it from the state vector */
140 if (vec != 0 && idx < (int)vec->get_element_count())
141 {
142 /* get the element */
143 vm_val_t ele;
144 vec->get_element(idx, &ele);
145
146 /* if it's a string, return it */
147 const char *str = ele.get_as_string(vmg0_);
148 if (str != 0)
149 {
150 len = vmb_get_len(str);
151 return str + VMB_LEN;
152 }
153 }
154
155 /* we didn't find it in the state vector; return the default */
156 if (idx < ndefaults)
157 {
158 len = strlen(defaults[idx]);
159 return defaults[idx];
160 }
161
162 /* invalid entry */
163 len = 0;
164 return 0;
165 }
166
167 /*
168 * Index a locale list. If 'sticky' is true, the last item actually
169 * present in the list will be returned if the index is past the end of
170 * the list.
171 */
172 const char *index_list(VMG_ size_t &itemlen, int item, int idx, int sticky)
173 {
174 /* get the item */
175 size_t len;
176 const char *str = get(vmg_ len, item);
177
178 /* if we didn't find it, return failure */
179 if (str == 0)
180 {
181 itemlen = 0;
182 return 0;
183 }
184
185 /* skip items (delimited by commas) until we reach the target index */
186 for ( ; idx > 0 && len != 0 ; --idx, ++str, --len)
187 {
188 /* find the next comma */
189 const char *comma = lib_strnchr(str, len, ',');
190 if (comma == 0)
191 {
192 /*
193 * No more commas, so the index is past the end of the
194 * list. If 'sticky' is true, use the last item; otherwise
195 * return "not found".
196 */
197 if (sticky)
198 break;
199 else
200 {
201 itemlen = 0;
202 return 0;
203 }
204 }
205
206 /* advance to the comma */
207 len -= comma - str;
208 str = comma;
209 }
210
211 /* we have the item; measure its length, up to the next '=' or ',' */
212 const char *p;
213 for (p = str, itemlen = 0 ; len != 0 && *p != '=' && *p != ',' ;
214 --len, ++p, ++itemlen) ;
215
216 /* return the item pointer */
217 return str;
218 }
219
220 /* set a locale string */
221 void set(VMG_ CVmUndo *undo, int idx, const vm_val_t *val)
222 {
223 /* if we don't have a vector, create one */
224 if (vec == 0)
225 {
226 /* create the vector */
227 vecid = CVmObjVector::create(vmg_ FALSE, ndefaults);
228 vec = vm_objid_cast(CVmObjVector, vecid);
229
230 /* initialize all elements to nil */
231 vm_val_t nil;
232 nil.set_nil();
233 for (int i = 0 ; i < ndefaults ; ++i)
234 vec->append_element(vmg_ vecid, &nil);
235
236 /* store the vector in the class object's state holder */
237 vm_val_t val;
238 val.set_obj(vecid);
239 vm_classobj_for(CVmObjDate)->set_class_state(&val);
240 }
241
242 /* if it's out of bounds, it's an error */
243 if (idx < 0 || idx >= ndefaults)
244 err_throw(VMERR_INDEX_OUT_OF_RANGE);
245
246 /* set the specified element */
247 vec->set_element_undo(vmg_ vecid, idx, val);
248 }
249
250 /* defaults */
251 static const char *defaults[];
252 static const int ndefaults;
253
254 /* our state Vector */
255 vm_obj_id_t vecid;
256 CVmObjVector *vec;
257 };
258
259 /* list of default locale settings */
260 const char *CVmDateLocale::defaults[] =
261 {
262 /* 0 - month full names */
263 "January,February,March,April,May,June,July,August,"
264 "September,October,November,December",
265
266 /* 1 - month name abbreviations */
267 "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep=Sept,Oct,Nov,Dec",
268
269 /* 2 - weekday full names */
270 "Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",
271
272 /* 3 - weekday abbreviations */
273 "Sun,Mon,Tue,Wed,Thu,Fri,Sat",
274
275 /* 4 - AM/PM indicators (upper, lower) */
276 "AM=A.M.,PM=P.M.,am,pm",
277
278 /* 5 - era (AD/BC) indicators */
279 "AD=A.D.=CE=C.E.,BC=B.C.=BCE=B.C.E.",
280
281 /* 6 - parsing format filter - 'us' or 'eu' */
282 "us",
283
284 /* 7 - ordinal suffixes */
285 "st,nd,rd,th,st,nd,rd",
286
287 /* 8 - timestamp format string */
288 "%a %b %#d %T %Y",
289
290 /* 9 - time format string */
291 "%H:%M:%S",
292
293 /* 10 - default date format */
294 "%m/%d/%Y",
295
296 /* 11 - short date format */
297 "%m/%d/%y",
298
299 /* 12 - 12-hour clock format */
300 "%#I:%M:%S %P",
301
302 /* 13 - 24-hour clock format */
303 "%H:%M",
304
305 /* 14 - 24-hour clock with seconds */
306 "%H:%M:%S"
307 };
308 const int CVmDateLocale::ndefaults = countof(CVmDateLocale::defaults);
309
310 /* locale indices */
311 static const int LC_MONTH = 0;
312 static const int LC_MON = 1;
313 static const int LC_WEEKDAY = 2;
314 static const int LC_WKDY = 3;
315 static const int LC_AMPM = 4;
316 static const int LC_ERA = 5;
317 static const int LC_PARSE_FILTER = 6;
318 static const int LC_ORDSUF = 7;
319 static const int LC_FMT_TIMESTAMP = 8;
320 static const int LC_FMT_TIME = 9;
321 static const int LC_FMT_DATE = 10;
322 static const int LC_FMT_SHORTDATE = 11;
323 static const int LC_FMT_12HOUR = 12;
324 static const int LC_FMT_24HOUR = 13;
325 static const int LC_FMT_24HOURSECS = 14;
326
327
328 /*
329 * Figure the ordinal suffix index (in LC_ORDSUF) for a given number. The
330 * suffix indices are:
331 *
332 *. 0 = 1st
333 *. 1 = 2nd
334 *. 2 = 3rd
335 *. 3 = Nth
336 *. 4 = X1st (e.g., 21st, 31st, 121st)
337 *. 5 = X2nd
338 *. 6 = X3rd
339 */
340 static int ordinal_index(int n)
341 {
342 /* get the last digit */
343 int lastdig = n % 10;
344
345 /*
346 * if it's in the teens, or the last digit is 0 or 4-9, use the generic
347 * Nth suffix
348 */
349 if (lastdig == 0 || lastdig >= 4 || (n > 10 && n < 20))
350 return 3;
351
352 /* if it's in the 1-3 range, use 1st/2nd/3rd; otherwise use X1st/etc */
353 return lastdig + (n < 10 ? -1 : 3);
354 }
355
356
357 /* ------------------------------------------------------------------------ */
358 /*
359 * Allocate an extension structure
360 */
361 vm_date_ext *vm_date_ext::alloc_ext(VMG_ CVmObjDate *self)
362 {
363 /* calculate how much space we need */
364 size_t siz = sizeof(vm_date_ext);
365
366 /* allocate the memory */
367 vm_date_ext *ext = (vm_date_ext *)G_mem->get_var_heap()->alloc_mem(
368 siz, self);
369
370 /* return the new extension */
371 return ext;
372 }
373
374 /* ------------------------------------------------------------------------ */
375 /*
376 * CVmObjDate object statics
377 */
378
379 /* metaclass registration object */
380 static CVmMetaclassDate metaclass_reg_obj;
381 CVmMetaclass *CVmObjDate::metaclass_reg_ = &metaclass_reg_obj;
382
383 /* function table */
384 int (CVmObjDate::*CVmObjDate::func_table_[])(
385 VMG_ vm_obj_id_t self, vm_val_t *retval, uint *argc) =
386 {
387 &CVmObjDate::getp_undef, /* 0 */
388 &CVmObjDate::getp_parseDate, /* 1 */
389 &CVmObjDate::getp_parseJulianDate, /* 2 */
390 &CVmObjDate::getp_formatDate, /* 3 */
391 &CVmObjDate::getp_formatJulianDate, /* 4 */
392 &CVmObjDate::getp_compareTo, /* 5 */
393 &CVmObjDate::getp_getDate, /* 6 */
394 &CVmObjDate::getp_getJulianDay, /* 7 */
395 &CVmObjDate::getp_getJulianDate, /* 8 */
396 &CVmObjDate::getp_getISOWeekDate, /* 9 */
397 &CVmObjDate::getp_getTime, /* 10 */
398 &CVmObjDate::getp_addInterval, /* 11 */
399 &CVmObjDate::getp_findWeekday, /* 12 */
400 &CVmObjDate::getp_setLocaleInfo /* 13 */
401 };
402
403 /* static property indices */
404 const int VMDATE_PARSEDATE = 1;
405 const int VMDATE_PARSEJULIANDATE = 2;
406 const int VMDATE_SETLOCALINFO = 13;
407
408 /* ------------------------------------------------------------------------ */
409 /*
410 * Construction
411 */
412 CVmObjDate::CVmObjDate(VMG_ int32_t dayno, uint32_t daytime)
413 {
414 /* allocate our extension structure */
415 vm_date_ext *ext = vm_date_ext::alloc_ext(vmg_ this);
416 ext_ = (char *)ext;
417
418 /* fill it in */
419 ext->dayno = dayno;
420 ext->daytime = daytime;
421 }
422
423 /* ------------------------------------------------------------------------ */
424 /*
425 * Get my date and time in the given local time zone
426 */
427 const char *CVmObjDate::get_local_time(
428 int32_t &dayno, int32_t &daytime, int32_t &ofs, CVmTimeZone *tz) const
429 {
430 /* get my UTC date and time */
431 dayno = get_ext()->dayno;
432 daytime = get_ext()->daytime;
433
434 /* convert to my local time zone */
435 return tz->utc_to_local(dayno, daytime, ofs);
436 }
437
438 /* ------------------------------------------------------------------------ */
439 /*
440 * Date/time parser
441 */
442
443 /* string capture item */
444 struct date_parse_string
445 {
446 date_parse_string() { p = 0; len = 0; }
447 void set(const char *p, size_t len) { this->p = p; this->len = len; }
448 const char *p;
449 size_t len;
450 };
451
452 /*
453 * Parse results structure. This keeps track of which information we've
454 * filled in so far.
455 */
456 struct date_parse_result
457 {
458 date_parse_result(multicaldate_t *cal)
459 {
460 /* remember my calendar interface */
461 this->cal = cal;
462
463 /*
464 * Initialize most elements to invalid, out-of-bounds values to
465 * indicate they haven't been set yet. INT_MIN satisfies this for
466 * all of these, so for the sake of clarity use it for all of them.
467 * For the month and day, only positive values are meaningful, so
468 * any negative value will suffice as the "invalid" token. The
469 * hour, minute, second, and milliseconds must be non-negative to
470 * be valid, so any negative value is invalid. The time zone
471 * offset must be between -24 hours (-24*60 minutes) and +24 hours
472 * (+24*60 minutes), so a large negative value is invalid. The
473 * year can mathematically be any integer value, but the ultimate
474 * representation of the date can only hold a 32-bit day number,
475 * which limits the year number to about +/-5 million; so INT_MIN,
476 * which is about minus 2 billion on a 32-bit machine, is a
477 * negative year that we can't represent. (This shouldn't be a big
478 * loss; prehistoric dates aren't very meaningful anyway, as there
479 * are by definition no historical records to correlate with
480 * calculated dates.) The timezone pointer is different in that
481 * it's a pointer, so null is the natural 'undefined' there.
482 */
483 era = 0;
484 yy = INT_MIN;
485 yy_needs_century = FALSE;
486 mm = INT_MIN;
487 dd = INT_MIN;
488
489 ampm = 0;
490 hh = INT_MIN;
491 mi = INT_MIN;
492 ss = INT_MIN;
493 ms = INT_MIN;
494 tzofs = INT_MIN;
495 w = INT_MIN;
496 tz = 0;
497 }
498
499 date_parse_result(date_parse_result &src)
500 {
501 memcpy(this, &src, sizeof(*this));
502 }
503
504 /* translate a time from local to UTC using our parsed timezone info */
505 void local_to_utc(int32_t &dayno, int32_t &daytime)
506 {
507 /*
508 * If we have a specific timezone offset, use the offset; otherwise
509 * translate via the time zone object.
510 *
511 * Note that it's possible for a parsed date to specify both an
512 * offset and a zone. If a seasonal zone abbreviation like "PDT"
513 * is used, it tells us both the timezone (America/Los_Angeles in
514 * the case of PDT) and the offset (-7 hours for PDT). The offset
515 * overrides the implied offset for the timezone because it
516 * specifies a particular seasonal time setting; if only the
517 * timezone is specified, we use the wall clock time for the zone.
518 * For example, "12/1/2000 3:00 America/Los_Angeles" has a -8 hour
519 * offset, since Pacific Standard Time is in effect in this zone in
520 * December, whereas "12/1/2000 3:00 PDT" has a -7 hour offset,
521 * since it's specfically a PDT time even though the wall clock
522 * time in Los Angeles in December is Pacific Standard Time.
523 */
524 if (has_tzofs())
525 {
526 /* we have an offset - it overrides the time zone */
527 daytime -= tzofs;
528 caldate_t::normalize(dayno, daytime);
529 }
530 else
531 {
532 /* no offset, so use the timezone */
533 tz->local_to_utc(dayno, daytime);
534 }
535 }
536
537 /* translate from UTC to local using our parsed timezone info */
538 void utc_to_local(int32_t &dayno, int32_t &daytime)
539 {
540 if (has_tzofs())
541 {
542 daytime += tzofs;
543 caldate_t::normalize(dayno, daytime);
544 }
545 else
546 {
547 int32_t ofs;
548 tz->utc_to_local(dayno, daytime, ofs);
549 }
550 }
551
552 /*
553 * set a default date - this sets any undefined date components
554 * individually from the given date
555 */
556 void def_date(int32_t dayno)
557 {
558 /* convert the day number to a calendar date */
559 cal->set_dayno(dayno);
560
561 /* apply the era to the year, if both are present */
562 if (era != 0 && has_year())
563 {
564 switch (era)
565 {
566 case 1:
567 /*
568 * astronomical '+' notation - the internal year number
569 * matches the nominal year
570 */
571 break;
572
573 case 2:
574 /*
575 * AD - the internal year matches the nominal year, but an
576 * explicit AD overrides the need for a century; e.g., AD
577 * 87 is pretty clear that we're talking about an
578 * historical date in the first century
579 */
580 yy_needs_century = FALSE;
581 break;
582
583 case -1:
584 /*
585 * astronomical '-' notation - the internal year number
586 * matches the nominal negative year number, since we use
587 * the same notation internally
588 */
589 yy = -yy;
590 break;
591
592 case -2:
593 /* BC - 1 BC is internal year 0, 2 BC is year -1, etc */
594 yy = -yy + 1;
595 yy_needs_century = FALSE;
596 break;
597 }
598 }
599
600 /* set the default year, month, and day from the given date */
601 def_year(cal->y());
602 def_month(cal->m());
603 def_day(cal->d());
604
605 /*
606 * If the year was specified without a century, choose the century
607 * such that it yields the year nearest to the current year. This
608 * is equivalent to finding the year within 50 years of the current
609 * year. For 2012, this makes the range 1962 to 2061 - so '62 is
610 * taken to be 1962, '85 is 1985, but '15 is 2015, and 61 is 2061.
611 */
612 if (yy_needs_century)
613 {
614 yy += ((cal->y() / 100) * 100);
615 if (yy < cal->y() - 50)
616 yy += 100;
617 if (yy > cal->y() + 49)
618 yy -= 100;
619 }
620 }
621
622 /*
623 * set a default time - this sets any undefined time components
624 * individually from the given time
625 */
626 void def_time(int m, int h, int s, int ms)
627 {
628 /* apply the PM indicator to the time, if present and in range */
629 if (ampm == 1 && hh == 12)
630 hh = 0;
631 else if (ampm == 2 && hh < 12)
632 hh += 12;
633
634 def_hour(h);
635 def_minute(m);
636 def_second(s);
637 def_msec(ms);
638 }
639
640 /* compute the day number */
641 int32_t dayno() const
642 {
643 /* if there's an ISO weekday, convert it to a calendar date */
644 if (has_iso_week() && has_year())
645 {
646 /*
647 * Calculate the "correction factor" - this is the ISO weekday
648 * number of January 4 of the year, plus 3. Note that this is
649 * explicitly defined as Jan 4 *Gregorian* by the standard, so
650 * this isn't relative to the calendar we're parsing for.
651 */
652 caldate_t jan4(yy, 1, 4);
653 int corr = jan4.iso_weekday() + 3;
654
655 /*
656 * Set the date to "January 'ord'", where 'ord' is the ISO
657 * ordinal day number calculated from the weekday and
658 * correction factor. This won't necessarily be a valid date
659 * in January, but caldate_t handles overflows in the day by
660 * carrying into the month and year as needed.
661 */
662 caldate_t cd(yy, 1, w - corr);
663 return cd.dayno();
664 }
665 else
666 {
667 /* set the calendar date to our year, month, and day */
668 cal->set_date(yy, mm, dd);
669
670 /* return the day number from the calendar date */
671 return cal->dayno();
672 }
673 }
674
675 /* compute the time of day */
676 int32_t daytime() const
677 {
678 return hh*60*60*1000 + mi*60*1000 + ss*1000 + ms;
679 }
680
681 /*
682 * Set defaults for the various components. These will set the
683 * component only if it hasn't been set to a valid value already.
684 */
685 void def_year(int y) { if (!has_year()) yy = y; }
686 void def_month(int m) { if (!has_month()) mm = m; }
687 void def_day(int d) { if (!has_day()) dd = d; }
688
689 void def_hour(int h) { if (!has_hour()) hh = h; }
690 void def_minute(int m) { if (!has_minute()) mi = m; }
691 void def_second(int s) { if (!has_second()) ss = s; }
692 void def_msec(int m) { if (!has_msec()) ms = m; }
693
694 void def_tzofs(int t) { if (!has_tzofs()) tzofs = t; }
695 void def_tz(CVmTimeZone *z) { if (!has_tz()) tz = z; }
696
697 /* default to the local time zone */
698 void def_local_tz(VMG0_)
699 {
700 if (!has_tz())
701 tz = G_tzcache->get_local_zone(vmg0_);
702 }
703
704 /* determine if the various elements are set */
705 int has_era() const { return era != 0; }
706 int has_year() const { return yy != INT_MIN; }
707 int has_month() const { return mm != INT_MIN; }
708 int has_day() const { return dd != INT_MIN; }
709 int has_iso_week() const { return w != INT_MIN; }
710
711 int has_ampm() const { return ampm != 0; }
712 int has_hour() const { return hh != INT_MIN; }
713 int has_minute() const { return mi != INT_MIN; }
714 int has_second() const { return ss != INT_MIN; }
715 int has_msec() const { return ms != INT_MIN; }
716
717 int has_tzofs() const { return tzofs != INT_MIN; }
718 int has_tz() const { return tz != 0; }
719
720 /* the calendar we're using to parse the date */
721 multicaldate_t *cal;
722
723 /* era: 1 = '+', 2 = AD, -1 = '-', -2 = BC */
724 int era;
725
726 /* date - year, month, day */
727 int yy;
728 int mm;
729 int dd;
730
731 /*
732 * ISO 8601 week+day - this is the value W*7+D from a date in ISO 8601
733 * format, where W is the week number (1-53) and D is the day of week
734 * number (1-7).
735 */
736 int w;
737
738 /* flag: the year was specified without a century */
739 int yy_needs_century;
740
741 /* time - hour, minute, second, milliseconds on 24-hour clock */
742 int ampm;
743 int hh;
744 int mi;
745 int ss;
746 int ms;
747
748 /* timezone */
749 CVmTimeZone *tz;
750
751 /* time zone by GMT offset, in milliseconds */
752 int tzofs;
753
754 /* string capture items for the various components */
755 date_parse_string pera, pyy, pmm, pdd, pdoy, pw;
756 date_parse_string pampm, phh, pmi, pss, pms, punix, ptz;
757 };
758
759
760 /* match a format element in a template string */
761 static inline int match_fmt(const char *fmt, const char *fmtend,
762 const char *ref)
763 {
764 size_t len = strlen(ref);
765 return (len == (size_t)(fmtend - fmt) && memcmp(ref, fmt, len) == 0);
766 }
767
768 /*
769 * match a digit string; the template gives pairs of digits with the bounds
770 * to match - e.g., "09" matches one digit from 0 to 9, "12" matches one
771 * digit from 1 to 2, "0209" matches 00 to 29, etc. We can also match ','
772 * to a period or comma.
773 */
774 static int match_digits(int &acc, const char *&str, size_t &len,
775 const char *tpl, date_parse_string &capture)
776 {
777 /* set up a private pointer to the string */
778 const char *p = str;
779 size_t rem = len;
780
781 /* match each template pair */
782 acc = 0;
783 for ( ; *tpl != '\0' ; tpl += 2, ++p, --rem)
784 {
785 /* check for the special match to a period or comma */
786 if (*tpl == ',')
787 {
788 /* back up to make up for the normal double increment */
789 --tpl;
790
791 /* allow it to match, but don't require it */
792 if (rem != 0 && (*p == ',' || *p == '.'))
793 continue;
794
795 /* it doesn't match; simply say on the same input character */
796 --p, ++rem;
797 continue;
798 }
799
800 /* if this input char isn't a digit, we don't have a match */
801 if (rem == 0 || !is_digit(*p))
802 return FALSE;
803
804 /* if this digit is out of range, it's not a match */
805 if (*p < tpl[0] || *p > tpl[1])
806 return FALSE;
807
808 /* matched this digit - add it to the accumulator */
809 acc *= 10;
810 acc += value_of_digit(*p);
811 }
812
813 /* set the capture data */
814 capture.p = str;
815 capture.len = p - str;
816
817 /* advance the caller's string pointers past the match */
818 str = p;
819 len = rem;
820
821 /* return success */
822 return TRUE;
823 }
824
825 /*
826 * match literal text
827 */
828 static int match_lit(const char *&str, size_t &len,
829 const char *lit, size_t litlen,
830 date_parse_string &capture)
831 {
832 /* if there's no literal, there's no match */
833 if (lit == 0)
834 return 0;
835
836 /* if the template starts with "^", it means do not fold case */
837 int fold_case = TRUE;
838 if (litlen != 0 && *lit == '^')
839 fold_case = FALSE, ++lit, --litlen;
840
841 /* try matching the template text */
842 size_t matchlen;
843 if (fold_case)
844 {
845 /* compare the leading substring of 'str' with case folding */
846 if (t3_compare_case_fold(lit, litlen, str, len, &matchlen) != 0)
847 return FALSE;
848 }
849 else if (len >= litlen)
850 {
851 /* compare exactly as given with no case folding */
852 if (memcmp(lit, str, litlen) != 0)
853 return FALSE;
854 matchlen = litlen;
855 }
856 else
857 {
858 /* it's too short to match */
859 return FALSE;
860 }
861
862 /* get a pointer to the next character after the end of the match */
863 utf8_ptr p((char *)str + matchlen);
864 size_t rem = len - matchlen;
865
866 /* make sure we ended on a suitable boundary */
867 if (rem != 0 && litlen != 0)
868 {
869 /* get the last character of the matched text */
870 wchar_t last = p.getch_before(1);
871 wchar_t next = p.getch();
872
873 /* if we ended on alphabetic, make sure the next is non-alpha */
874 if (isalpha(last) && isalpha(next))
875 return FALSE;
876
877 /* if we ended on a number, maek sure the next is non-numeric */
878 if (isdigit(last) && isdigit(next))
879 return FALSE;
880 }
881
882 /* set the capture data */
883 capture.p = str;
884 capture.len = p.getptr() - str;
885
886 /* advance the caller's string pointers past the match */
887 str = p.getptr();
888 len = rem;
889
890 /* return success */
891 return TRUE;
892 }
893 static int match_lit(const char *&str, size_t &len, const char *lit,
894 date_parse_string &capture)
895 {
896 return match_lit(str, len, lit, lit != 0 ? strlen(lit) : 0, capture);
897 }
898
899 /*
900 * Match literal text from a list. The list is given as a string of
901 * comma-separated elements, ending with a semicolon. Elements can have
902 * aliases specified with '=', as in "sep=sept, ...". Spaces after commas
903 * are ignored.
904 */
905 static int match_list(int &acc, const char *&str, size_t &len,
906 const char *lst, size_t lstlen,
907 date_parse_string &capture)
908 {
909 /* no matches yet */
910 int bestlen = 0;
911 int bestidx = 0;
912
913 /* skip leading spaces */
914 for ( ; lstlen != 0 && is_space(*lst) ; ++lst, --lstlen) ;
915
916 /* keep going until we're out of list */
917 for (int idx = 1 ; lstlen != 0 ; )
918 {
919 /* find the next delimiter */
920 const char *p = lst;
921 size_t rem = lstlen;
922 for ( ; rem != 0 && *p != '=' && *p != ',' && *p != ';' ; ++p, --rem) ;
923
924 /* try matching this text */
925 const char *curstr = str;
926 size_t curlen = len;
927 date_parse_string part;
928 if (p - lst != 0 && match_lit(curstr, curlen, lst, p - lst, part))
929 {
930 /* if this is the best one so far, remember it */
931 if (curstr - str > bestlen)
932 {
933 bestlen = curstr - str;
934 bestidx = idx;
935 }
936 }
937
938 /*
939 * If we're at an '=', an alias for this same item follows, so keep
940 * going without upping the index. If we're at a comma, we're on
941 * to the next item. If we're at a ';' or the end of the string,
942 * it's the end of the list, so we've failed to find a match.
943 */
944 if (rem == 0 || *p == ';')
945 {
946 /* end of the list */
947 break;
948 }
949 else if (*p == ',')
950 {
951 /* next list item follows - up the index */
952 ++idx;
953
954 /* skip the comma and any spaces before the next item */
955 for (++p, --rem ; rem != 0 && is_space(*p) ; ++p, --rem) ;
956 }
957 else if (*p == '=')
958 {
959 /* alias - just skip the '=' */
960 ++p, --rem;
961 }
962
963 /* on to the next item */
964 lst = p;
965 lstlen = rem;
966 }
967
968 /* if we found a match, return it */
969 if (bestlen != 0)
970 {
971 capture.p = str;
972 capture.len = bestlen;
973 acc = bestidx;
974 str += bestlen;
975 len -= bestlen;
976 return TRUE;
977 }
978 else
979 return FALSE;
980 }
981
982 /*
983 * match a timezone offset - [GMT] +/- hh [:][mi] [:][ss]
984 */
985 static int match_tzofs(VMG_ date_parse_result *res,
986 const char *&str, size_t &len)
987 {
988 const char *p = str;
989 size_t rem = len;
990
991 /* first, skip "gmt" if present */
992 date_parse_string part;
993 int gmtlit = match_lit(p, rem, "^GMT", part);
994
995 /* get the sign */
996 if (rem == 0 || (*p != '+' && *p != '-'))
997 return FALSE;
998 int s = (*p == '+' ? 1 : -1);
999
1000 /* skip the sign */
1001 ++p, --rem;
1002
1003 /*
1004 * Get the "hh". If the "GMT" literal was present, allow a single
1005 * digit; otherwise require the two-digit format.
1006 */
1007 int hh;
1008 if (!match_digits(hh, p, rem, "0509", part)
1009 && (!gmtlit || !match_digits(hh, p, rem, "09", part)))
1010 return FALSE;
1011
1012 /*
1013 * check for ":" - if present, the minutes must be present, otherwise
1014 * they're optional
1015 */
1016 int mi = 0;
1017 if (rem != 0 && *p == ':')
1018 {
1019 /* skip the ":", then require the minutes */
1020 ++p, --rem;
1021 if (!match_digits(mi, p, rem, "0509", part))
1022 return FALSE;
1023 }
1024 else
1025 {
1026 /* no ":", so the minuts are optional */
1027 match_digits(mi, p, rem, "0509", part);
1028 }
1029
1030 /* likewise, check for ":ss" */
1031 int ss = 0;
1032 if (rem != 0 && *p == ':')
1033 {
1034 ++p, --rem;
1035 if (!match_digits(ss, p, rem, "0509", part))
1036 return FALSE;
1037 }
1038 else
1039 {
1040 match_digits(ss, p, rem, "0509", part);
1041 }
1042
1043 /* success - figure the offset in seconds */
1044 int32_t ofs = s * ((hh*60*60) + (mi*60) + ss);
1045
1046 /* look up the zone by offset */
1047 res->tz = G_tzcache->get_gmtofs_zone(vmg_ ofs);
1048
1049 /* also set the explicit offset value (in milliseconds) */
1050 res->tzofs = ofs * 1000;
1051
1052 /* set the capture data */
1053 res->ptz.p = str;
1054 res->ptz.len = p - str;
1055
1056 /* advance the caller's vars past the parsed tzofs and return success */
1057 str = p;
1058 len = rem;
1059 return TRUE;
1060 }
1061
1062 /*
1063 * Match a timezone by name
1064 */
1065 static int match_tzname(VMG_ date_parse_result *res,
1066 const char *&str, size_t &len)
1067 {
1068 /* check for a zone name string ("America/Los_Angeles", etc) */
1069 if (len != 0 && isalpha(*str))
1070 {
1071 const char *p = str;
1072 size_t rem = len;
1073 for ( ; rem != 0 ; ++p, --rem)
1074 {
1075 /* allow letters, or / or _ if followed by a letter */
1076 if (isalpha(*p)
1077 || ((*p == '_' || *p == '/')
1078 && rem > 1 && isalpha(p[1])))
1079 continue;
1080
1081 /* otherwise we're done */
1082 break;
1083 }
1084
1085 /* if it contains a slash, look up the zoneinfo database name */
1086 CVmTimeZone *tz = 0;
1087 if (lib_strnchr(str, p - str, '/') != 0)
1088 {
1089 if ((tz = G_tzcache->get_db_zone(vmg_ str, p - str)) != 0)
1090 {
1091 /* success - this is a valid timezone name */
1092 res->ptz.p = str;
1093 res->ptz.len = p - str;
1094 str = p;
1095 len = rem;
1096 res->tz = tz;
1097 return TRUE;
1098 }
1099 }
1100
1101 /* didn't find a zone name; try an abbreviation */
1102 int32_t tzofs;
1103 tz = G_tzcache->get_zone_by_abbr(vmg_ &tzofs, str, p - str);
1104 if (tz != 0)
1105 {
1106 /*
1107 * Success - we found an abbreviation; this usually gives us
1108 * both a timezone and a specific offset, since an abbreviation
1109 * is specific to standard or daylight time. However, some
1110 * abbreviations don't specify an offset, since they're used in
1111 * the same zone for both standard and daylight time (e.g.,
1112 * Australian EST); these are flagged by tzofs coming back as
1113 * INT32MINVAL.
1114 */
1115 res->ptz.p = str;
1116 res->ptz.len = p - str;
1117 str = p;
1118 len = rem;
1119 res->tz = tz;
1120 if (tzofs != INT32MINVAL)
1121 res->tzofs = tzofs;
1122 return TRUE;
1123 }
1124 }
1125
1126 /* not a time zone */
1127 return FALSE;
1128 }
1129
1130 /*
1131 * Parse a date/time string against a given template
1132 */
1133 int CVmObjDate::parse_string_fmt(VMG_ date_parse_result *res,
1134 const char *&str, size_t &len,
1135 const char *fmt, size_t fmtl,
1136 CVmDateLocale *lc)
1137 {
1138 /* skip leading spaces and tabs in the source string */
1139 for ( ; len != 0 && is_space(*str) ; ++str, --len) ;
1140
1141 /* run through the format string */
1142 while (len != 0)
1143 {
1144 /* skip leading spaces in the format string */
1145 for ( ; fmtl != 0 && *fmt == ' ' ; --fmtl, ++fmt) ;
1146
1147 /* stop if we're at the end of the string */
1148 if (fmtl == 0)
1149 break;
1150
1151 /* find the next space or end of string */
1152 const char *sp = lib_strnchr(fmt, fmtl, ' ');
1153 sp = (sp != 0 ? sp : fmt + fmtl);
1154
1155 /* parse the type */
1156 switch (fmt[0])
1157 {
1158 case 'd':
1159 if (match_fmt(fmt, sp, "d"))
1160 {
1161 /* one- or two-digit day of month */
1162 int acc;
1163 if (match_digits(acc, str, len, "0209", res->pdd)
1164 || match_digits(acc, str, len, "3301", res->pdd)
1165 || match_digits(acc, str, len, "09", res->pdd))
1166 res->dd = acc;
1167 else
1168 return FALSE;
1169 }
1170 else if (match_fmt(fmt, sp, "dd"))
1171 {
1172 /* two-digit day of month */
1173 int acc;
1174 if (match_digits(acc, str, len, "0009", res->pdd)
1175 || match_digits(acc, str, len, "1209", res->pdd)
1176 || match_digits(acc, str, len, "3301", res->pdd))
1177 res->dd = acc;
1178 else
1179 return FALSE;
1180 }
1181 else if (match_fmt(fmt, sp, "ddth"))
1182 {
1183 /* one/two-digit day of month, plus optional ordinal suffix */
1184 int acc;
1185 if (match_digits(acc, str, len, "0209", res->pdd)
1186 || match_digits(acc, str, len, "3301", res->pdd)
1187 || match_digits(acc, str, len, "09", res->pdd))
1188 res->dd = acc;
1189 else
1190 return FALSE;
1191
1192 /* get the locale ordinal for the digit */
1193 size_t ordl;
1194 const char *ord = lc->index_list(
1195 vmg_ ordl, LC_ORDSUF, ordinal_index(acc), TRUE);
1196
1197 /* compare it */
1198 date_parse_string pdd;
1199 if (match_lit(str, len, ord, ordl, pdd))
1200 {
1201 /* matched - add this into the capture data */
1202 res->pdd.len += pdd.len;
1203 }
1204 }
1205 else if (match_fmt(fmt, sp, "doy"))
1206 {
1207 /* day of year */
1208 int acc;
1209 if (match_digits(acc, str, len, "000019", res->pdoy)
1210 || match_digits(acc, str, len, "001909", res->pdoy)
1211 || match_digits(acc, str, len, "120909", res->pdoy)
1212 || match_digits(acc, str, len, "330509", res->pdoy)
1213 || match_digits(acc, str, len, "336606", res->pdoy))
1214 {
1215 /*
1216 * set the date to January 'doy' - this isn't
1217 * necessarily a valid calendar date in January, but
1218 * caldate_t handles overflows in the day by carrying
1219 * to the month and year as needed
1220 */
1221 res->mm = 1;
1222 res->dd = acc;
1223 }
1224 }
1225 else
1226 goto other;
1227 break;
1228
1229 case 'm':
1230 if (match_fmt(fmt, sp, "month"))
1231 {
1232 /*
1233 * Month by long name, short name, or Roman numeral. Get
1234 * the locale strings for the month names; the Roman
1235 * numerals are fixed, so we can set up a static string for
1236 * those.
1237 */
1238 size_t mm_long_len, mm_abbr_len;
1239 const char *mm_long = lc->get(vmg_ mm_long_len, LC_MONTH);
1240 const char *mm_abbr = lc->get(vmg_ mm_abbr_len, LC_MON);
1241 static const char *romans =
1242 "^I,^II,^III,^IV,^V,^VI,^VII,^VIII,^IX,^X,^XI,^XII;";
1243
1244 /* try each variation */
1245 int acc;
1246 if (match_list(acc, str, len, mm_long, mm_long_len, res->pmm)
1247 || match_list(
1248 acc, str, len, mm_abbr, mm_abbr_len, res->pmm)
1249 || match_list(
1250 acc, str, len, romans, strlen(romans), res->pmm))
1251 res->mm = acc;
1252 else
1253 return FALSE;
1254
1255 /* specifying a month makes the default day the 1st */
1256 res->def_day(1);
1257 }
1258 else if (match_fmt(fmt, sp, "mon"))
1259 {
1260 /* month by short name */
1261 size_t mm_abbr_len;
1262 const char *mm_abbr = lc->get(vmg_ mm_abbr_len, LC_MON);
1263 int acc;
1264 if (match_list(acc, str, len, mm_abbr, mm_abbr_len, res->pmm))
1265 res->mm = acc;
1266 else
1267 return FALSE;
1268
1269 /* specifying a month makes the default day the 1st */
1270 res->def_day(1);
1271 }
1272 else if (match_fmt(fmt, sp, "m"))
1273 {
1274 /* one- or two-digit month */
1275 int acc;
1276 if (match_digits(acc, str, len, "0009", res->pmm)
1277 || match_digits(acc, str, len, "1102", res->pmm)
1278 || match_digits(acc, str, len, "09", res->pmm))
1279 res->mm = acc;
1280 else
1281 return FALSE;
1282
1283 /* specifying a month makes the default day the 1st */
1284 res->def_day(1);
1285 }
1286 else if (match_fmt(fmt, sp, "mm"))
1287 {
1288 /* two-digit month */
1289 int acc;
1290 if (match_digits(acc, str, len, "0009", res->pmm)
1291 || match_digits(acc, str, len, "1102", res->pmm))
1292 res->mm = acc;
1293 else
1294 return FALSE;
1295
1296 /* specifying a month makes the default day the 1st */
1297 res->def_day(1);
1298 }
1299 else if (match_fmt(fmt, sp, "mi"))
1300 {
1301 /* two-digit minutes */
1302 int acc;
1303 if (match_digits(acc, str, len, "0509", res->pmi))
1304 res->mi = acc;
1305 else
1306 return FALSE;
1307
1308 /* specifying the minute makes the default ss.frac zero */
1309 res->def_second(0);
1310 res->def_msec(0);
1311 }
1312 else
1313 goto other;
1314 break;
1315
1316 case 'W':
1317 if (match_fmt(fmt, sp, "W"))
1318 {
1319 /*
1320 * ISO week - a two-digit number giving the week of the
1321 * year, optionally followed by a day number
1322 */
1323 int w;
1324 if (match_digits(w, str, len, "0019", res->pw)
1325 || match_digits(w, str, len, "1409", res->pw)
1326 || match_digits(w, str, len, "5503", res->pw))
1327 {
1328 /* check for a weekday following */
1329 int d = 1;
1330 if (len >= 2
1331 && *str == '-'
1332 && strchr("1234567", str[1]) != 0)
1333 {
1334 d = value_of_digit(str[1]);
1335 str += 2, len -= 2;
1336 res->pw.len += 2;
1337 }
1338 else if (len >= 1 && strchr("1234567", str[0]) != 0)
1339 {
1340 d = value_of_digit(str[0]);
1341 str += 1, len -= 1;
1342 res->pw.len += 1;
1343 }
1344
1345 /* matched */
1346 res->w = w*7 + d;
1347 return TRUE;
1348 }
1349 else
1350 return FALSE;
1351 }
1352 else
1353 goto other;
1354 break;
1355
1356 case 'y':
1357 if (match_fmt(fmt, sp, "y"))
1358 {
1359 /* one- to seven-digit year */
1360 int acc;
1361 if (match_digits(acc, str, len, "09,090909,090909", res->pyy)
1362 || match_digits(acc, str, len, "090909,090909", res->pyy)
1363 || match_digits(acc, str, len, "0909,090909", res->pyy)
1364 || match_digits(acc, str, len, "09090909", res->pyy)
1365 || match_digits(acc, str, len, "090909", res->pyy))
1366 res->yy = acc;
1367 else if (match_digits(acc, str, len, "0909", res->pyy)
1368 || match_digits(acc, str, len, "09", res->pyy))
1369 {
1370 res->yy = acc;
1371 res->yy_needs_century = TRUE;
1372
1373 if (res->yy >= 5879650 || res->yy <= -5879650)
1374 err_throw(VMERR_NUM_OVERFLOW);
1375 }
1376 else
1377 return FALSE;
1378
1379 /* specifying the year makes the default date 1/1 */
1380 res->def_month(1);
1381 res->def_day(1);
1382 }
1383 else if (match_fmt(fmt, sp, "yy"))
1384 {
1385 /* two-digit year; century comes from the reference year */
1386 int acc;
1387 if (match_digits(acc, str, len, "0909", res->pyy))
1388 {
1389 res->yy = acc;
1390 res->yy_needs_century = TRUE;
1391 }
1392 else
1393 return FALSE;
1394
1395 /* specifying the year makes the default date 1/1 */
1396 res->def_month(1);
1397 res->def_day(1);
1398 }
1399 else if (match_fmt(fmt, sp, "yyyy"))
1400 {
1401 /* four-digit year */
1402 int acc;
1403 if (match_digits(acc, str, len, "09090909", res->pyy))
1404 res->yy = acc;
1405 else
1406 return FALSE;
1407
1408 /* specifying the year makes the default date 1/1 */
1409 res->def_month(1);
1410 res->def_day(1);
1411 }
1412 else if (match_fmt(fmt, sp, "ye"))
1413 {
1414 /*
1415 * Year with optional era designator (AD/BC). The era can
1416 * come before or after the year, with spaces in between.
1417 */
1418 size_t era_len;
1419 const char *era_lst = lc->get(vmg_ era_len, LC_ERA);
1420 int idx;
1421 int era = 0;
1422 if (match_list(idx, str, len, era_lst, era_len, res->pera))
1423 {
1424 /* note the era - 2 for AD, -2 for BC */
1425 res->era = era = (idx == 1 ? 2 : -2);
1426
1427 /* allow spaces */
1428 for ( ; len != 0 && isspace(*str) ; ++str, --len) ;
1429 }
1430
1431 /* match the year - this part is required */
1432 int acc;
1433 if (match_digits(acc, str, len, "09,090909,090909", res->pyy)
1434 || match_digits(acc, str, len, "090909,090909", res->pyy)
1435 || match_digits(acc, str, len, "0909,090909", res->pyy)
1436 || match_digits(acc, str, len, "09090909", res->pyy)
1437 || match_digits(acc, str, len, "090909", res->pyy)
1438 || match_digits(acc, str, len, "0909", res->pyy)
1439 || match_digits(acc, str, len, "09", res->pyy))
1440 res->yy = acc;
1441 else
1442 return FALSE;
1443
1444 /* we accept large year numbers, so check range */
1445 if (res->yy >= 5879650 || res->yy <= -5879650)
1446 err_throw(VMERR_NUM_OVERFLOW);
1447
1448 /* if we didn't have a prefixed era, check for a postfix era */
1449 if (era == 0)
1450 {
1451 /* skip optional spaces */
1452 const char *str2 = str;
1453 size_t len2 = len;
1454 for ( ; len2 != 0 && isspace(*str2) ; ++str2, --len2) ;
1455
1456 /* check for the era */
1457 if (match_list(
1458 idx, str2, len2, era_lst, era_len, res->pera))
1459 {
1460 /* found it - set the era identifier */
1461 res->era = era = (idx == 1 ? 2 : -2);
1462
1463 /* advance past it in the main string */
1464 str = str2;
1465 len = len2;
1466 }
1467 }
1468
1469 /*
1470 * if we matched one or two digits, with no era, we need a
1471 * default century
1472 */
1473 if (era == 0 && res->pyy.len <= 2)
1474 res->yy_needs_century = TRUE;
1475 }
1476 else
1477 goto other;
1478 break;
1479
1480 case 'e':
1481 if (match_fmt(fmt, sp, "era"))
1482 {
1483 /* AD/BC era designator */
1484 size_t era_len;
1485 const char *era_lst = lc->get(vmg_ era_len, LC_ERA);
1486 int idx;
1487 if (match_list(idx, str, len, era_lst, era_len, res->pera))
1488 {
1489 /* set the era to 2 for AD or -2 for BC */
1490 res->era = (idx == 1 ? 2 : -2);
1491 }
1492 else
1493 return FALSE;
1494 }
1495 else
1496 goto other;
1497 break;
1498
1499 case 'h':
1500 if (match_fmt(fmt, sp, "h"))
1501 {
1502 /* one- or two-digit hours */
1503 int acc;
1504 if (match_digits(acc, str, len, "0019", res->phh)
1505 || match_digits(acc, str, len, "1102", res->phh)
1506 || match_digits(acc, str, len, "09", res->phh))
1507 res->hh = acc;
1508 else
1509 return FALSE;
1510
1511 /* specifying the hour makes the default mm:ss.frac zero */
1512 res->def_minute(0);
1513 res->def_second(0);
1514 res->def_msec(0);
1515 }
1516 else if (match_fmt(fmt, sp, "hh"))
1517 {
1518 /* two-digit hours */
1519 int acc;
1520 if (match_digits(acc, str, len, "0109", res->phh)
1521 || match_digits(acc, str, len, "2204", res->phh))
1522 res->hh = acc;
1523 else
1524 return FALSE;
1525
1526 /* specifying the hour makes the default minute zero */
1527 res->def_minute(0);
1528 res->def_second(0);
1529 res->def_msec(0);
1530 }
1531 else
1532 goto other;
1533 break;
1534
1535 case 'i':
1536 if (match_fmt(fmt, sp, "i"))
1537 {
1538 /* one- or two-digit minutes */
1539 int acc;
1540 if (match_digits(acc, str, len, "0509", res->pmi)
1541 || match_digits(acc, str, len, "09", res->pmi))
1542 res->mi = acc;
1543 else
1544 return FALSE;
1545
1546 /* specifying the minute makes the default ss.frac zero */
1547 res->def_second(0);
1548 res->def_msec(0);
1549 }
1550 else
1551 goto other;
1552 break;
1553
1554 case 's':
1555 if (match_fmt(fmt, sp, "ss"))
1556 {
1557 /* two-digit seconds */
1558 int acc;
1559 if (match_digits(acc, str, len, "0509", res->pss))
1560 res->ss = acc;
1561 else
1562 return FALSE;
1563
1564 /* specifying the second makes the default fraction zero */
1565 res->def_msec(0);
1566 }
1567 else if (match_fmt(fmt, sp, "s"))
1568 {
1569 /* one- or two-digit seconds */
1570 int acc;
1571 if (match_digits(acc, str, len, "0509", res->pss)
1572 || match_digits(acc, str, len, "09", res->pss))
1573 res->ss = acc;
1574 else
1575 return FALSE;
1576
1577 /* specifying the second makes the default fraction zero */
1578 res->def_msec(0);
1579 }
1580 else if (match_fmt(fmt, sp, "ssfrac"))
1581 {
1582 /* fractional seconds */
1583 if (len >= 1 && isdigit(str[1]))
1584 {
1585 /*
1586 * parse digits - accumulate up to four digits so that
1587 * we can round to milliseconds
1588 */
1589 res->pms.p = str;
1590 res->pms.len = 0;
1591 int acc = 0, mul = 10000, trailing = 0;
1592 for ( ; len != 0 && isdigit(*str) ;
1593 ++str, --len, ++res->pms.len, mul /= 10)
1594 {
1595 /*
1596 * add the next digit only if significant,
1597 * otherwise note any non-zero trailing digits
1598 */
1599 if (mul > 1)
1600 acc *= 10, acc += value_of_digit(*str);
1601 else if (*str != '0')
1602 trailing = 1;
1603 }
1604
1605 /* apply the multiplier if non-zero */
1606 if (mul != 0)
1607 acc *= mul;
1608
1609 /* we have 10*ms - divide by 10 to get ms */
1610 int lastdig = acc % 10;
1611 acc /= 10;
1612
1613 /*
1614 * round up if the last digit is 6+, 5+ with a non-zero
1615 * digit following, or exactly 5 with an odd second
1616 * digit
1617 */
1618 if (lastdig > 5
1619 || (lastdig == 5
1620 && (trailing
1621 || ((acc % 10) & 1) != 0)))
1622 ++acc;
1623
1624 /* store as integer milliseconds */
1625 res->ms = acc;
1626 }
1627 else
1628 return FALSE;
1629 }
1630 else
1631 goto other;
1632 break;
1633
1634 case 'u':
1635 if (match_fmt(fmt, sp, "unix"))
1636 {
1637 /*
1638 * Unix timestamp value - any number of digits giving a
1639 * positive or negative offset in seconds from the Unix
1640 * Epoch (1/1/1970)
1641 */
1642 int s = 1;
1643 if (len >= 2 && str[0] == '-' && is_digit(str[1]))
1644 {
1645 res->punix.p = str, res->punix.len = 1;
1646 s = -1, ++str, --len;
1647 }
1648 else if (len >= 1 && is_digit(str[0]))
1649 {
1650 res->punix.p = str, res->punix.len = 0;
1651 }
1652 else
1653 return FALSE;
1654
1655 /*
1656 * Parse digits; use a double in case we have more than a
1657 * 32-bit int's worth. (We only work in whole integers
1658 * here, but we might need more precision than an int32. A
1659 * double is enough for any day we can represent: we have a
1660 * 32-bit day; 86400 seconds per day is about 17 additional
1661 * bits, for a total of 49. An IEEE double has a 52-bit
1662 * mantissa, so a double can exactly represent a Unix
1663 * timestamp for any day number we can represent.)
1664 */
1665 double acc = 0.0;
1666 for ( ; len > 0 && is_digit(*str) ;
1667 ++str, --len, ++res->punix.len)
1668 {
1669 acc *= 10.0;
1670 acc += value_of_digit(*str);
1671 }
1672
1673 /* apply the sign */
1674 acc *= s;
1675
1676 /* split into days and seconds */
1677 double days = floor(acc / (24.*60.*60.));
1678 int32_t secs = (int32_t)fmod(acc, 24.*60.*60.);
1679
1680 /* make sure it fits an int32 */
1681 if (days > INT32MAXVAL)
1682 return FALSE;
1683
1684 /*
1685 * convert to a calendar date, adjusting from the Unix
1686 * Epoch to our Epoch
1687 */
1688 res->cal->set_dayno(
1689 (int32_t)days + caldate_t::UNIX_EPOCH_DAYNO);
1690
1691 /* set the time and day in the parse results */
1692 res->yy = res->cal->y();
1693 res->mm = res->cal->m();
1694 res->dd = res->cal->d();
1695
1696 res->hh = secs/(60*60);
1697 res->mi = (secs/60) % 60;
1698 res->ss = secs % 60;
1699 res->ms = 0;
1700
1701 /* Unix timestamps are relative to UTC */
1702 res->tzofs = 0;
1703 }
1704 else
1705 goto other;
1706 break;
1707
1708 case 'a':
1709 if (match_fmt(fmt, sp, "ampm"))
1710 {
1711 /* month by short name */
1712 size_t ampm_len;
1713 const char *ampm_str = lc->get(vmg_ ampm_len, LC_AMPM);
1714 int acc;
1715 if (match_list(acc, str, len, ampm_str, ampm_len, res->pampm))
1716 res->ampm = acc;
1717 else
1718 return FALSE;
1719 }
1720 else
1721 goto other;
1722 break;
1723
1724 case 't':
1725 if (match_fmt(fmt, sp, "tz"))
1726 {
1727 /* timezone by name, abbreviation, or offset */
1728 if (!match_tzofs(vmg_ res, str, len)
1729 && !match_tzname(vmg_ res, str, len))
1730 return FALSE;
1731 }
1732 else
1733 goto other;
1734 break;
1735
1736 case 'g':
1737 if (match_fmt(fmt, sp, "gmtofs"))
1738 {
1739 /* timezone offset from GMT */
1740 if (!match_tzofs(vmg_ res, str, len))
1741 return FALSE;
1742 }
1743 else
1744 goto other;
1745 break;
1746
1747 default:
1748 other:
1749 if (match_fmt(fmt, sp, "+-"))
1750 {
1751 /*
1752 * Astronomical-notation era designator - this is the
1753 * system where the year before AD 1 is Year 0, the year
1754 * before that -1, etc. Positive years can optionally have
1755 * a plus sign.
1756 */
1757 if (match_lit(str, len, "+", res->pera))
1758 res->era = 1;
1759 else if (match_lit(str, len, "-", res->pera))
1760 res->era = -1;
1761 else
1762 return FALSE;
1763 }
1764 else
1765 {
1766 /*
1767 * Anything else is a list of literals to match. If it
1768 * ends with '*', we can match zero or more; if it ends
1769 * with '+', we can match one or more; otherwise we match
1770 * exactly one.
1771 */
1772 const char *fmtend = sp;
1773 char suffix = *(sp-1);
1774 int mincnt = (suffix == '*' || suffix == '?' ? 0 : 1);
1775 int maxcnt = (suffix == '*' || suffix == '+' ? 65535 : 1);
1776 fmtend -= (strchr("*?+", suffix) != 0 ? 1 : 0);
1777
1778 /* scan the character list */
1779 int cnt = 0;
1780 utf8_ptr strp((char *)str);
1781 while (cnt < maxcnt && len != 0)
1782 {
1783 int found = FALSE;
1784 utf8_ptr fmtp((char *)fmt);
1785 for ( ; fmtp.getptr() < fmtend ; fmtp.inc())
1786 {
1787 /* get the current template and source characters */
1788 wchar_t fc = fmtp.getch();
1789 wchar_t sc = strp.getch();
1790
1791 /*
1792 * check for specials: \ quotes the next, _ is a
1793 * space
1794 */
1795 if (fc == '\\' && fmtp.getptr() < fmtend)
1796 {
1797 fmtp.inc();
1798 fc = fmtp.getch();
1799 }
1800 else if (fc == '_')
1801 {
1802 fc = ' ';
1803 }
1804
1805 /* check for a match */
1806 if (fc == sc)
1807 {
1808 found = TRUE;
1809 ++cnt;
1810 strp.inc(&len);
1811 str = strp.getptr();
1812 break;
1813 }
1814 }
1815 if (!found)
1816 break;
1817 }
1818
1819 /* if we didn't match the minimum number, it's a mismatch */
1820 if (cnt < mincnt)
1821 return FALSE;
1822 }
1823 break;
1824 }
1825
1826 /* advance past this field */
1827 fmtl -= sp - fmt;
1828 fmt = sp;
1829 }
1830
1831 /* if we didn't exhaust the format, we have no match */
1832 if (fmtl != 0)
1833 return FALSE;
1834
1835 /* we matched the format - skip trailing spaces */
1836 for ( ; len != 0 && is_space(*str) ; ++str, --len) ;
1837
1838 /* return success */
1839 return TRUE;
1840 }
1841
1842 /* custom/builtin format string iterator */
1843 struct format_iter
1844 {
1845 format_iter(VMG_ const char **builtin, size_t builtin_cnt,
1846 const vm_val_t *custom)
1847 {
1848 /* save the source lists */
1849 this->builtin = builtin;
1850 this->builtin_cnt = builtin_cnt;
1851 this->custom = custom;
1852
1853 /* presume we'll start in the custom list */
1854 this->mode = 0;
1855
1856 /* figure how many builtin items we have, if any */
1857 if (custom == 0 || custom->typ == VM_NIL)
1858 {
1859 /* no custom items - just use the builtin list */
1860 this->custom_cnt = 0;
1861 this->mode = 1;
1862 }
1863 else if (custom->get_as_string(vmg0_) != 0)
1864 this->custom_cnt = 1;
1865 else if (custom->is_listlike(vmg0_))
1866 this->custom_cnt = custom->ll_length(vmg0_);
1867 else
1868 err_throw(VMERR_BAD_TYPE_BIF);
1869
1870 /* start at the top of each list */
1871 this->bidx = 0;
1872 this->cidx = 0;
1873 }
1874
1875 /* get the next string */
1876 const char *next(VMG_ size_t &len)
1877 {
1878 /* assume we won't find anythign */
1879 len = 0;
1880
1881 /* keep going until we find something */
1882 for (;;)
1883 {
1884 if (mode == 0)
1885 {
1886 /* custom list - if exhausted, we're done */
1887 if (cidx >= custom_cnt)
1888 return 0;
1889
1890 /* get the next custom item, according to the source type */
1891 vm_val_t ele;
1892 if (custom->is_listlike(vmg0_))
1893 {
1894 /* get the next list element */
1895 custom->ll_index(vmg_ &ele, ++cidx);
1896
1897 /* if it's nil, switch to the builtin list */
1898 if (ele.typ == VM_NIL)
1899 {
1900 mode = 1;
1901 continue;
1902 }
1903 }
1904 else
1905 {
1906 /* it must be a single string */
1907 ele = *custom;
1908 }
1909
1910 /* retrieve the string value */
1911 const char *str = ele.get_as_string(vmg0_);
1912 if (str != 0)
1913 {
1914 len = vmb_get_len(str);
1915 str += VMB_LEN;
1916 }
1917 return str;
1918 }
1919 else
1920 {
1921 /* builtin list - if exhausted, return to the custom list */
1922 if (bidx >= builtin_cnt)
1923 {
1924 mode = 0;
1925 continue;
1926 }
1927
1928 /* return the next builtin item */
1929 len = strlen(builtin[bidx]);
1930 return builtin[bidx++];
1931 }
1932 }
1933 }
1934
1935 /* current list we're reading from - 0=custom, 1=builtin */
1936 int mode;
1937
1938 /* builtin list, and current index in list */
1939 const char **builtin;
1940 size_t builtin_cnt;
1941 size_t bidx;
1942
1943 /* custom string or list, and current index in list */
1944 const vm_val_t *custom;
1945 size_t custom_cnt;
1946 size_t cidx;
1947 };
1948
1949 /*
1950 * Parse a date string in a constructor argument.
1951 */
1952 int CVmObjDate::parse_date_string(
1953 VMG_ int32_t &dayno, int32_t &daytime,
1954 const char *str, const vm_val_t *custom, CVmDateLocale *lc,
1955 multicaldate_t *cal, int32_t refday, int32_t reftime, CVmTimeZone *reftz,
1956 date_parse_result *resultp, date_parse_string *fmtlist, int *nfmtlist)
1957 {
1958 /* get the string length and buffer */
1959 size_t len = vmb_get_len(str);
1960 str += VMB_LEN;
1961
1962 /* format list */
1963 static const char *fmt[] =
1964 {
1965 /* US-style dates, with the month first */
1966 "[us]m / d / y",
1967 "[us]m / d",
1968 "[us]m - d",
1969 "[us]m . d",
1970 "[us]m .\t- d .\t- y",
1971
1972 /* European-style date formats, with day/month order */
1973 "[eu]d / m / y",
1974 "[eu]d / m",
1975 "[eu]d - m",
1976 "[eu]d . m",
1977 "[eu]d .\t- m .\t- y",
1978
1979 /* match some special computer formats first */
1980 "yyyy mm dd", /* 8-digit year month day */
1981 "yyyy .? doy", /* PostreSQL year with day-of-year */
1982
1983 /* universal date formats */
1984 "m / y",
1985 "m - y",
1986 "month _.\t-* ddth _,.\t+ ye",
1987 "ddth _.\t-* month _,.\t-* ye",
1988 "month _.\t-* ddth",
1989 "ddth _.\t-* month",
1990 "month - dd - ye",
1991 "month _\t.-* y",
1992 "month",
1993 "+- y - mm - dd",
1994 "y / m / d",
1995 "y - m - d",
1996 "y / m",
1997 "y - m",
1998 "ye _\t.-* month _\t.-* d",
1999 "ye _\t.-* month",
2000 "ye - month - dd",
2001 "yyyy",
2002 "era _* y",
2003 "y _* era",
2004
2005 /* time formats */
2006 "h _? ampm",
2007 "h : mi",
2008 "h .: mi _? ampm",
2009 "h .: mi .: ss _? ampm",
2010 "h : mi : ss",
2011 "h : mi : ss .: ssfrac _? ampm",
2012 "h : mi : ss .: ssfrac",
2013 "tT? hh .: mi",
2014 "tT? hh mi",
2015 "tT? hh .: mi .: ss",
2016 "tT? hh mi SS",
2017 "tT? hh .: mi .: ss _? tz",
2018 "tT? hh .: mi .: ss . ssfrac",
2019 "tz",
2020
2021 /* special formats (ISO, other software, etc) */
2022 "d / mon / yyyy : hh : mi : ss _ gmtofs", /* Unix log files */
2023 "yyyy : mm : dd _ hh : mi : ss", /* EXIF */
2024 "yyyy -? \\W W", /* ISO year with ISO week */
2025 "yyyy - mm - dd \\T hh : mi : ss . ssfrac", /* SOAP */
2026 "yyyy - mm - dd \\T hh : mi : ss . ssfrac gmtofs", /* SOAP */
2027 "@ unix", /* Unix timestamp */
2028 "yyyy mm dd \\T hh : mi : ss", /* XMLRPC */
2029 "yyyy mm dd \\t hh mi ss", /* XMLRPC - compact */
2030 "yyyy - m - d \\T h : i : s" /* WDDX */
2031 };
2032
2033 /* get the template filter in "[xx]" format */
2034 size_t filterlen;
2035 const char *filter = lc->get(vmg_ filterlen, LC_PARSE_FILTER);
2036
2037 /* keep separate results for each pass */
2038 date_parse_result result(cal);
2039
2040 /*
2041 * Run through the format list as many times as it takes to either
2042 * consume the whole source string, or fail to find a matching format.
2043 * We have multiple format parts that can be specified individually or
2044 * in combination (time, date, time + date, date + time, etc).
2045 */
2046 int fcapi;
2047 for (fcapi = 0 ; len != 0 ; ++fcapi)
2048 {
2049 /* we haven't found a best result for this pass yet */
2050 int bestlen = 0;
2051 date_parse_result bestres(cal);
2052
2053 /* search the list for a match */
2054 format_iter fi(vmg_ fmt, countof(fmt), custom);
2055 size_t curfmtl;
2056 const char *curfmt;
2057 while ((curfmt = fi.next(vmg_ curfmtl)) != 0)
2058 {
2059 /* set up at the current position */
2060 const char *curstr = str;
2061 size_t curlen = len;
2062
2063 /* remember the original format string */
2064 const char *curfmt0 = curfmt;
2065 size_t curfmtl0 = curfmtl;
2066
2067 /* if this is a "[us]" or "[eu]" local entry, filter it */
2068 if (curfmtl >= 3 && curfmt[0] == '[')
2069 {
2070 /* get the ']' */
2071 const char *rb = lib_strnchr(curfmt+1, curfmtl-1, ']');
2072
2073 /*
2074 * if we found it, and the contents of the brackets don't
2075 * match the locale filter string, filter out this format
2076 */
2077 if (rb != 0
2078 && (rb - curfmt - 1 != (int)filterlen
2079 || memicmp(curfmt + 1, filter, filterlen) != 0))
2080 continue;
2081
2082 /* skip the filter string */
2083 curfmtl -= rb - curfmt + 1;
2084 curfmt = rb + 1;
2085 }
2086
2087 /* start with the results from previous passes */
2088 date_parse_result curres(result);
2089
2090 /* try matching this format at the current position */
2091 if (parse_string_fmt(vmg_ &curres, curstr, curlen,
2092 curfmt, curfmtl, lc))
2093 {
2094 /* if this is the longest match of this pass, keep it */
2095 int reslen = curstr - str;
2096 if (reslen > bestlen)
2097 {
2098 /* remember this as the best result so far */
2099 bestlen = reslen;
2100 bestres = curres;
2101
2102 /* remember the format string it matches, if desired */
2103 if (nfmtlist != 0 && fcapi < *nfmtlist)
2104 fmtlist[fcapi].set(curfmt0, curfmtl0);
2105 }
2106 }
2107 }
2108
2109 /* if we didn't find a match on this round, we've failed */
2110 if (bestlen == 0)
2111 return FALSE;
2112
2113 /* skip what we matched for the best result of this pass */
2114 str += bestlen;
2115 len -= bestlen;
2116
2117 /* keep the best result for this pass */
2118 result = bestres;
2119
2120 /* skip spaces and other separator characters */
2121 for ( ; len != 0 && strchr(" \t;,:", *str) != 0 ; ++str, --len) ;
2122 }
2123
2124 /* default to the reference time zone */
2125 result.def_tz(reftz);
2126
2127 /* adjust the reference time to the appropriate local time zone */
2128 result.utc_to_local(refday, reftime);
2129
2130 /* set missing date elements to the corresponding reference date values */
2131 result.def_date(refday);
2132
2133 /* set any missing time elements to midnight or zero past the hour/min */
2134 result.def_time(0, 0, 0, 0);
2135
2136 /* convert to our internal day and time representation */
2137 dayno = result.dayno();
2138 daytime = result.daytime();
2139 caldate_t::normalize(dayno, daytime);
2140
2141 /* translate the final time value from the specified local time to UTC */
2142 result.local_to_utc(dayno, daytime);
2143
2144 /* copy back the results if the caller's interested */
2145 if (resultp != 0)
2146 memcpy(resultp, &result, sizeof(result));
2147
2148 /* tell the caller how many format strings we matched, if desired */
2149 if (nfmtlist != 0)
2150 *nfmtlist = fcapi;
2151
2152 /* success */
2153 return TRUE;
2154 }
2155
2156 /*
2157 * Parse constructor arguments for a (...Y,M,D) or (...Y,M,D,HH,MI,SS,MS)
2158 * argument list. This parses the arguments from the stack and fills in
2159 * the day number and time of day values accordingly. We don't make any
2160 * time zone adjustments; we just return the value as specified.
2161 */
2162 static void parse_ymd_args(VMG_ int argofs, int argc,
2163 int32_t &dayno, int32_t &daytime)
2164 {
2165 /* get the year, month, and day */
2166 int32_t y = G_stk->get(argofs + 0)->num_to_int(vmg0_);
2167 int32_t m = G_stk->get(argofs + 1)->num_to_int(vmg0_);
2168 int32_t d = G_stk->get(argofs + 2)->num_to_int(vmg0_);
2169
2170 /* figure the day number for the given calendar date */
2171 caldate_t cd(y, m, d);
2172 dayno = cd.dayno();
2173
2174 /*
2175 * if this is the 7-argument version, get the time; otherwise it's
2176 * implicitly midnight on the given date
2177 */
2178 daytime = 0;
2179 if (argc == 7)
2180 {
2181 /* get the hour and minute as integers, and seconds */
2182 int hh = G_stk->get(argofs + 3)->num_to_int(vmg0_);
2183 int mm = G_stk->get(argofs + 4)->num_to_int(vmg0_);
2184 int ss = G_stk->get(argofs + 5)->num_to_int(vmg0_);
2185 int ms = G_stk->get(argofs + 6)->num_to_int(vmg0_);
2186
2187 /*
2188 * Combine the time components into 'daytime' in milliseconds.
2189 * This could be a very large number, so work in double until we
2190 * can normalize it. Note that we're working in whole numbers only
2191 * (no fractions), so a double will be exact - all we're worried
2192 * about here is the extra integer precision it can hold, not the
2193 * fractional part.
2194 */
2195 double dt = hh*60.*60.*1000. + mm*60.*1000. + ss*1000. + ms;
2196
2197 /* figure the overflow into the day number (and make sure it fits) */
2198 double dd = floor(dt / (24.*60.*60.*1000.));
2199 dt = fmod(dt, 24.*60.*60.*1000.);
2200
2201 /* apply the overflow to the day number, and make sure it fits */
2202 dd += dayno;
2203 if (dd < INT32MINVAL || dd > INT32MAXVAL)
2204 err_throw(VMERR_NUM_OVERFLOW);
2205
2206 /* it's all normalized and in range, so convert back to int32 */
2207 dayno = (int32_t)dd;
2208 daytime = (int32_t)dt;
2209 }
2210
2211 /* normalize the result */
2212 caldate_t::normalize(dayno, daytime);
2213 }
2214
2215 /* ------------------------------------------------------------------------ */
2216 /*
2217 * Create with a given timestamp
2218 */
2219 vm_obj_id_t CVmObjDate::create(VMG_ int in_root_set,
2220 int32_t dayno, int32_t daytime)
2221 {
2222 vm_obj_id_t id = vm_new_id(vmg_ in_root_set, FALSE, FALSE);
2223 new (vmg_ id) CVmObjDate(vmg_ dayno, daytime);
2224 return id;
2225 }
2226
2227 /* ------------------------------------------------------------------------ */
2228 /*
2229 * Create from an os_time_t timestamp
2230 */
2231 vm_obj_id_t CVmObjDate::create_from_time_t(VMG_ int in_root_set, os_time_t t)
2232 {
2233 /*
2234 * turn the time_t into days and milliseconds after the Unix Epoch (use
2235 * doubles to ensure we don't overflow an int)
2236 */
2237 double d = (double)t;
2238 double dn = floor(d / (24*60*60));
2239 double dms = (d - (dn * (24*60*60))) * 1000;
2240
2241 /* adjust to our internal Epoch */
2242 dn += caldate_t::UNIX_EPOCH_DAYNO;
2243
2244 /* we have the time in our own format now, so go create the object */
2245 return create(vmg_ in_root_set, (int32_t)dn, (int32_t)dms);
2246 }
2247
2248 /* ------------------------------------------------------------------------ */
2249 /*
2250 * create dynamically using stack arguments
2251 */
2252 vm_obj_id_t CVmObjDate::create_from_stack(VMG_ const uchar **pc_ptr, uint argc)
2253 {
2254 int32_t dayno;
2255 int32_t daytime;
2256 const char *str;
2257
2258 /* check for the various argument lists */
2259 if (argc == 0)
2260 {
2261 /* no arguments - get the current date and time in the local zone */
2262 caldate_t::now(dayno, daytime);
2263 }
2264 else if ((argc >= 1 && argc <= 3)
2265 && (str = G_stk->get(0)->get_as_string(vmg0_)) != 0)
2266 {
2267 /*
2268 * The first argument is a date in string format. The optional
2269 * second argument is the reference time zone; the optional third
2270 * argument is the reference date.
2271 */
2272
2273 /* get the reference time zone */
2274 CVmTimeZone *reftz;
2275 if (argc >= 2 && G_stk->get(1)->typ != VM_NIL)
2276 reftz = get_tz_arg(vmg_ 1, argc);
2277 else
2278 reftz = G_tzcache->get_local_zone(vmg0_);
2279
2280 /* get the reference date */
2281 int32_t refday, reftime;
2282 if (argc >= 3 && G_stk->get(2)->typ != VM_NIL)
2283 {
2284 /* get the reference Date object */
2285 CVmObjDate *refdate = vm_val_cast(CVmObjDate, G_stk->get(2));
2286 if (refdate == 0)
2287 err_throw(VMERR_BAD_TYPE_BIF);
2288
2289 /* take the reference point from the Date object */
2290 refday = refdate->get_ext()->dayno;
2291 reftime = refdate->get_ext()->daytime;
2292 }
2293 else
2294 {
2295 /* no reference date, so use the current time */
2296 caldate_t::now(refday, reftime);
2297 }
2298
2299 /* parse the format */
2300 CVmDateLocale lc Pvmg0_P;
2301 gregcaldate_t cal;
2302 if (!parse_date_string(vmg_ dayno, daytime, str, 0, &lc, &cal,
2303 refday, reftime, reftz, 0, 0, 0))
2304 err_throw(VMERR_BAD_VAL_BIF);
2305 }
2306 else if (argc == 2
2307 && G_stk->get(0)->is_numeric(vmg0_)
2308 && (str = G_stk->get(1)->get_as_string(vmg0_)) != 0)
2309 {
2310 /* check the type code */
2311 double dn, dms;
2312 if (vmb_get_len(str) == 1 && (str[2] == 'U' || str[2] == 'u'))
2313 {
2314 /*
2315 * 'U' - Unix time, as seconds past 1/1/1970, UTC. Get the
2316 * argument as a double, and convert it to our day numbering
2317 * scheme by dividing by seconds per day and adding the Unix
2318 * Epoch's day number. (An ordinary double is big enough to
2319 * hold the largest Unix seconds-since-Epoch value we can
2320 * represent: our range is limited by the 32-bit day number, so
2321 * in terms of seconds that's (2^31-1)*86400, which needs about
2322 * 49 bits. A standard double's mantissa is 52 bits, so it can
2323 * represent any integer in our range exactly.)
2324 */
2325 double d = G_stk->get(0)->num_to_double(vmg0_);
2326 dn = floor(d / (24*60*60));
2327 dms = (d - (dn * (24*60*60))) * 1000;
2328 dn += caldate_t::UNIX_EPOCH_DAYNO;
2329 }
2330 else if (vmb_get_len(str) == 1 && (str[2] == 'J' || str[2] == 'j'))
2331 {
2332 /*
2333 * 'J' - Julian day number; get the value, and adjust it to our
2334 * Epoch by subtracting the Julian day number of our Epoch.
2335 * The whole part is our day number; the fractional part is the
2336 * fraction of a day past midnight (the .5 in the Epoch
2337 * adjustment recalibrates from noon to midnight).
2338 */
2339 bignum_t<32> bdayno(vmg_ G_stk->get(0));
2340 bdayno -= 1721119.5;
2341 dn = floor((double)bdayno);
2342 dms = (double)((bdayno - dn) * (long)(24*60*60*1000));
2343 }
2344 else
2345 {
2346 /* unrecognized code */
2347 err_throw(VMERR_BAD_VAL_BIF);
2348 }
2349
2350 /* make sure the day number fits an int32 */
2351 if (dn > INT32MAXVAL || dn < INT32MINVAL)
2352 err_throw(VMERR_NUM_OVERFLOW);
2353 dayno = (int32_t)dn;
2354
2355 /* convert milliseconds to int32 */
2356 daytime = round_int32(dms);
2357 }
2358 else if ((argc == 3 || argc == 7)
2359 && G_stk->get(0)->is_numeric(vmg0_)
2360 && G_stk->get(1)->is_numeric(vmg0_)
2361 && G_stk->get(2)->is_numeric(vmg0_)
2362 && (argc == 3
2363 || (G_stk->get(3)->is_numeric(vmg0_)
2364 && G_stk->get(4)->is_numeric(vmg0_)
2365 && G_stk->get(5)->is_numeric(vmg0_)
2366 && G_stk->get(6)->is_numeric(vmg0_))))
2367 {
2368 /* parse the Y/M/D or Y/M/D HH:MI:SS arguments */
2369 parse_ymd_args(vmg_ 0, argc, dayno, daytime);
2370
2371 /* convert from the local time zone to UTC */
2372 G_tzcache->get_local_zone(vmg0_)->local_to_utc(dayno, daytime);
2373 }
2374 else if ((argc == 4 || argc == 8)
2375 && G_stk->get(0)->is_numeric(vmg0_)
2376 && G_stk->get(1)->is_numeric(vmg0_)
2377 && G_stk->get(2)->is_numeric(vmg0_)
2378 && (argc == 4
2379 || (G_stk->get(3)->is_numeric(vmg0_)
2380 && G_stk->get(4)->is_numeric(vmg0_)
2381 && G_stk->get(5)->is_numeric(vmg0_)
2382 && G_stk->get(6)->is_numeric(vmg0_))))
2383 {
2384 /* parse the Y/M/D or Y/M/D HH:MI:SS arguments */
2385 parse_ymd_args(vmg_ 0, argc - 1, dayno, daytime);
2386
2387 /* convert from the given time zone to UTC */
2388 get_tz_arg(vmg_ argc - 1, argc)->local_to_utc(dayno, daytime);
2389 }
2390 else
2391 {
2392 /* wrong arguments */
2393 err_throw(VMERR_BAD_TYPE_BIF);
2394 }
2395
2396 /* create the object */
2397 vm_obj_id_t id = vm_new_id(vmg_ FALSE, FALSE, FALSE);
2398 new (vmg_ id) CVmObjDate(vmg_ dayno, daytime);
2399
2400 /* discard arguments */
2401 G_stk->discard(argc);
2402
2403 /* return the new ID */
2404 return id;
2405 }
2406
2407 /* ------------------------------------------------------------------------ */
2408 /*
2409 * notify of deletion
2410 */
2411 void CVmObjDate::notify_delete(VMG_ int /*in_root_set*/)
2412 {
2413 /* free our additional data, if we have any */
2414 if (ext_ != 0)
2415 G_mem->get_var_heap()->free_mem(ext_);
2416 }
2417
2418 /* ------------------------------------------------------------------------ */
2419 /*
2420 * set a property
2421 */
2422 void CVmObjDate::set_prop(VMG_ class CVmUndo *undo,
2423 vm_obj_id_t self, vm_prop_id_t prop,
2424 const vm_val_t *val)
2425 {
2426 /* no settable properties - throw an error */
2427 err_throw(VMERR_INVALID_SETPROP);
2428 }
2429
2430 /* ------------------------------------------------------------------------ */
2431 /*
2432 * get a property
2433 */
2434 int CVmObjDate::get_prop(VMG_ vm_prop_id_t prop, vm_val_t *retval,
2435 vm_obj_id_t self, vm_obj_id_t *source_obj,
2436 uint *argc)
2437 {
2438 uint func_idx;
2439
2440 /* translate the property into a function vector index */
2441 func_idx = G_meta_table
2442 ->prop_to_vector_idx(metaclass_reg_->get_reg_idx(), prop);
2443
2444 /* call the appropriate function */
2445 if ((this->*func_table_[func_idx])(vmg_ self, retval, argc))
2446 {
2447 *source_obj = metaclass_reg_->get_class_obj(vmg0_);
2448 return TRUE;
2449 }
2450
2451 /* inherit default handling from our base class */
2452 return CVmObject::get_prop(vmg_ prop, retval, self, source_obj, argc);
2453 }
2454
2455 /*
2456 * get a static (class) property
2457 */
2458 int CVmObjDate::call_stat_prop(VMG_ vm_val_t *result,
2459 const uchar **pc_ptr, uint *argc,
2460 vm_prop_id_t prop)
2461 {
2462 /* look up the function */
2463 uint midx = G_meta_table
2464 ->prop_to_vector_idx(metaclass_reg_->get_reg_idx(), prop);
2465
2466 /* check for our static properties */
2467 switch (midx)
2468 {
2469 case VMDATE_PARSEDATE:
2470 return s_getp_parseDate(vmg_ result, argc);
2471
2472 case VMDATE_PARSEJULIANDATE:
2473 return s_getp_parseJulianDate(vmg_ result, argc);
2474
2475 case VMDATE_SETLOCALINFO:
2476 return s_getp_setLocaleInfo(vmg_ result, argc);
2477 }
2478
2479 /* not one of hours; inherit the superclass handling */
2480 return CVmObject::call_stat_prop(vmg_ result, pc_ptr, argc, prop);
2481 }
2482
2483 /* ------------------------------------------------------------------------ */
2484 /*
2485 * cast to a string
2486 */
2487 const char *CVmObjDate::cast_to_string(
2488 VMG_ vm_obj_id_t self, vm_val_t *newstr) const
2489 {
2490 /* format the date into a buffer */
2491 char buf[64];
2492 format_string_buf(vmg_ buf, sizeof(buf));
2493
2494 /* create the return string */
2495 newstr->set_obj(CVmObjString::create(vmg_ FALSE, buf, strlen(buf)));
2496 return newstr->get_as_string(vmg0_);
2497 }
2498
2499 /*
2500 * Format into a string buffer using the default representation - for
2501 * implied conversions, toString, and the debugger
2502 */
2503 void CVmObjDate::format_string_buf(VMG_ char *buf, size_t buflen) const
2504 {
2505 /* get the day number and time of day in local time */
2506 int32_t dayno, daytime, tzofs;
2507 const char *tzabbr = get_local_time(
2508 dayno, daytime, tzofs, G_tzcache->get_local_zone(vmg0_));
2509
2510 /* convert the day number to a calendar date */
2511 gregcaldate_t date(dayno);
2512
2513 /* format using a default template */
2514 CVmDateLocale lc Pvmg0_P;
2515 format_date(vmg_ buf, buflen, "%Y-%m-%d %H:%M:%S", 17, &lc,
2516 &date, dayno, daytime, tzabbr, tzofs);
2517 }
2518
2519 /* ------------------------------------------------------------------------ */
2520 /*
2521 * Date arithmetic - add an integer or BigNumber: adds the given number of
2522 * days to the date.
2523 */
2524 int CVmObjDate::add_val(VMG_ vm_val_t *result, vm_obj_id_t /*self*/,
2525 const vm_val_t *val)
2526 {
2527 /* get my date and time */
2528 int32_t dayno = get_ext()->dayno;
2529 int32_t daytime = get_ext()->daytime;
2530
2531 /* the other value must be something numeric */
2532 if (val->typ == VM_INT)
2533 {
2534 /* it's a simple integer - add it as a number of days */
2535 dayno += val->val.intval;
2536 }
2537 else
2538 {
2539 /* it's not an int; calculate in the bignum domain */
2540 bignum_t<32>d(vmg_ val);
2541
2542 /* make sure the integer portion won't overflow */
2543 double dd = floor((double)d);
2544 if (dd + dayno > INT32MAXVAL || dd + dayno < INT32MINVAL)
2545 err_throw(VMERR_NUM_OVERFLOW);
2546
2547 /* add the whole part to my day number */
2548 dayno += (int32_t)dd;
2549
2550 /*
2551 * convert the fractional part to milliseconds (by multiplying it
2552 * by the number of milliseconds in a day), then add it to my time
2553 * value
2554 */
2555 daytime += round_int32((double)((d - dd) * (long)(24L*60*60*1000)));
2556
2557 /* normalize, to carry time overflow/underflow into the date */
2558 caldate_t::normalize(dayno, daytime);
2559 }
2560
2561 /* return a new Date object representing the result */
2562 result->set_obj(create(vmg_ FALSE, dayno, daytime));
2563
2564 /* handled */
2565 return TRUE;
2566 }
2567
2568 /* ------------------------------------------------------------------------ */
2569 /*
2570 * Date arithmetic - subtract an integer or BigNumber to subtract a number
2571 * of days from the date; or subtract another Date value to calculate the
2572 * number of days between the dates.
2573 */
2574 int CVmObjDate::sub_val(VMG_ vm_val_t *result, vm_obj_id_t /*self*/,
2575 const vm_val_t *val)
2576 {
2577 /* get my date and time */
2578 int32_t dayno = get_ext()->dayno;
2579 int32_t daytime = get_ext()->daytime;
2580
2581 /* the other value must be a Date or something numeric */
2582 if (val->typ == VM_OBJ && is_date_obj(vmg_ val->val.obj))
2583 {
2584 /* get the other date's contents */
2585 CVmObjDate *vdate = (CVmObjDate *)vm_objp(vmg_ val->val.obj);
2586 int32_t vdayno = vdate->get_ext()->dayno;
2587 int32_t vdaytime = vdate->get_ext()->daytime;
2588
2589 /* we need fractional days, so calculate as bignum_t */
2590 bignum_t<32> d1((long)dayno), t1((long)daytime);
2591 bignum_t<32> d2((long)vdayno), t2((long)vdaytime);
2592 d1 += (t1 / (long)(24*60*60*1000));
2593 d2 += (t2 / (long)(24*60*60*1000));
2594
2595 /* return a BigNumber containing the result */
2596 result->set_obj(CVmObjBigNum::create(vmg_ FALSE, d1 - d2));
2597
2598 /* handled (we don't want to return a Date, as the other paths do) */
2599 return TRUE;
2600 }
2601 else if (val->typ == VM_INT)
2602 {
2603 /* it's a simple integer - subtract the number of days */
2604 dayno -= val->val.intval;
2605 }
2606 else
2607 {
2608 /* it's not an int; calculate in the bignum domain */
2609 bignum_t<32> d(vmg_ val);
2610
2611 /* make sure the integer portion won't overflow */
2612 double dd = floor((double)d);
2613 if (dd - dayno > INT32MAXVAL || dd - dayno < INT32MINVAL)
2614 err_throw(VMERR_NUM_OVERFLOW);
2615
2616 /* add the whole part to my day number */
2617 dayno -= (int32_t)dd;
2618
2619 /*
2620 * convert the fractional part to milliseconds (by multiplying it
2621 * by the number of milliseconds in a day), then subtract it from
2622 * my time value
2623 */
2624 daytime -= round_int32((double)((d - dd) * (long)(24L*60*60*1000)));
2625
2626 /* normalize, to carry time overflow/underflow into the date */
2627 caldate_t::normalize(dayno, daytime);
2628 }
2629
2630 /* return a new Date object representing the result */
2631 result->set_obj(create(vmg_ FALSE, dayno, daytime));
2632
2633 /* handled */
2634 return TRUE;
2635 }
2636
2637
2638 /* ------------------------------------------------------------------------ */
2639 /*
2640 * Check two Date values for equality
2641 */
2642 int CVmObjDate::equals(VMG_ vm_obj_id_t, const vm_val_t *val, int) const
2643 {
2644 if (val->typ == VM_OBJ && is_date_obj(vmg_ val->val.obj))
2645 {
2646 /* it's a Date - get the two day number and time values */
2647 CVmObjDate *vdate = (CVmObjDate *)vm_objp(vmg_ val->val.obj);
2648 int32_t day1 = get_ext()->dayno, day2 = vdate->get_ext()->dayno;
2649 int32_t time1 = get_ext()->daytime, time2 = vdate->get_ext()->daytime;
2650
2651 /* we're equal if we represent the same date and time */
2652 return day1 == day2 && time1 == time2;
2653 }
2654 else
2655 {
2656 /* we're not equal to any other type */
2657 return FALSE;
2658 }
2659 }
2660
2661
2662 /*
2663 * Compare two Date values
2664 */
2665 int CVmObjDate::compare_to(VMG_ vm_obj_id_t, const vm_val_t *val) const
2666 {
2667 /* check the other object's type */
2668 if (val->typ == VM_OBJ && is_date_obj(vmg_ val->val.obj))
2669 {
2670 /* it's a Date - get the two day number and time values */
2671 CVmObjDate *vdate = (CVmObjDate *)vm_objp(vmg_ val->val.obj);
2672 int32_t day1 = get_ext()->dayno, day2 = vdate->get_ext()->dayno;
2673 int32_t time1 = get_ext()->daytime, time2 = vdate->get_ext()->daytime;
2674
2675 /* compare by date and time */
2676 return (day1 != day2 ? day1 - day2 : time1 - time2);
2677 }
2678 else
2679 {
2680 /* we can't compare to other types */
2681 err_throw(VMERR_INVALID_COMPARISON);
2682 AFTER_ERR_THROW(return 0;)
2683 }
2684 }
2685
2686
2687 /* ------------------------------------------------------------------------ */
2688 /*
2689 * load from an image file
2690 */
2691 void CVmObjDate::load_from_image(VMG_ vm_obj_id_t self,
2692 const char *ptr, size_t siz)
2693 {
2694 /* load our image data */
2695 load_image_data(vmg_ ptr, siz);
2696
2697 /*
2698 * save our image data pointer in the object table, so that we can
2699 * access it (without storing it ourselves) during a reload
2700 */
2701 G_obj_table->save_image_pointer(self, ptr, siz);
2702 }
2703
2704 /*
2705 * reload from the image file
2706 */
2707 void CVmObjDate::reload_from_image(VMG_ vm_obj_id_t self,
2708 const char *ptr, size_t siz)
2709 {
2710 /* load our image data */
2711 load_image_data(vmg_ ptr, siz);
2712 }
2713
2714 /*
2715 * load or reload data from the image
2716 */
2717 void CVmObjDate::load_image_data(VMG_ const char *ptr, size_t siz)
2718 {
2719 /* free our existing extension, if we have one */
2720 if (ext_ != 0)
2721 G_mem->get_var_heap()->free_mem(ext_);
2722
2723 /* allocate the extension */
2724 vm_date_ext *ext = vm_date_ext::alloc_ext(vmg_ this);
2725 ext_ = (char *)ext;
2726
2727 /* read the image data */
2728 ext->dayno = osrp4s(ptr);
2729 ext->daytime = osrp4(ptr+4);
2730 }
2731
2732
2733 /*
2734 * save to a file
2735 */
2736 void CVmObjDate::save_to_file(VMG_ class CVmFile *fp)
2737 {
2738 /* get our extension */
2739 vm_date_ext *ext = get_ext();
2740
2741 /* write the extension data */
2742 fp->write_int4(ext->dayno);
2743 fp->write_uint4(ext->daytime);
2744 }
2745
2746 /*
2747 * restore from a file
2748 */
2749 void CVmObjDate::restore_from_file(VMG_ vm_obj_id_t self,
2750 CVmFile *fp, CVmObjFixup *)
2751 {
2752 /* free our existing extension, if we have one */
2753 if (ext_ != 0)
2754 G_mem->get_var_heap()->free_mem(ext_);
2755
2756 /* allocate the extension structure */
2757 vm_date_ext *ext = vm_date_ext::alloc_ext(vmg_ this);
2758 ext_ = (char *)ext;
2759
2760 /* read the data */
2761 ext->dayno = fp->read_int4();
2762 ext->daytime = fp->read_uint4();
2763 }
2764
2765 /* ------------------------------------------------------------------------ */
2766 /*
2767 * Construct a list of integer values for return from a method
2768 */
2769 static void make_int_list(VMG_ vm_val_t *retval, int cnt, ...)
2770 {
2771 /* create the list */
2772 retval->set_obj(CVmObjList::create(vmg_ FALSE, cnt));
2773 CVmObjList *lst = (CVmObjList *)vm_objp(vmg_ retval->val.obj);
2774
2775 /* start the varargs scan */
2776 va_list args;
2777 va_start(args, cnt);
2778
2779 /* add the elements */
2780 for (int i = 0 ; i < cnt ; ++i)
2781 {
2782 vm_val_t ele;
2783 ele.set_int(va_arg(args, int));
2784 lst->cons_set_element(i, &ele);
2785 }
2786
2787 /* done with the varargs */
2788 va_end(args);
2789 }
2790
2791 /*
2792 * Add a string to a return list
2793 */
2794 static void enlist_str(VMG_ CVmObjList *lst, int idx,
2795 const char *str, size_t len)
2796 {
2797 /* set up a new string, or nil if the string is null */
2798 vm_val_t ele;
2799 if (str != 0)
2800 ele.set_obj(CVmObjString::create(vmg_ FALSE, str, len));
2801 else
2802 ele.set_nil();
2803
2804 /* add the list element */
2805 lst->cons_set_element(idx, &ele);
2806 }
2807
2808 /* add a string from a date_parse_string */
2809 static void enlist_str(VMG_ CVmObjList *lst, int idx,
2810 const date_parse_string &str)
2811 {
2812 enlist_str(vmg_ lst, idx, str.p, str.len);
2813 }
2814
2815 /* ------------------------------------------------------------------------ */
2816 /*
2817 * parseDate method (static)
2818 */
2819 int CVmObjDate::s_getp_parseDate(VMG_ vm_val_t *retval, uint *oargc)
2820 {
2821 /* parse the date using the Gregorian calendar */
2822 gregcaldate_t cal;
2823 return common_parseDate(vmg_ retval, oargc, &cal);
2824 }
2825
2826 /*
2827 * parseJulianDate method (static)
2828 */
2829 int CVmObjDate::s_getp_parseJulianDate(VMG_ vm_val_t *retval, uint *oargc)
2830 {
2831 /* parse the date using the Julian calendar */
2832 julcaldate_t cal;
2833 return common_parseDate(vmg_ retval, oargc, &cal);
2834 }
2835
2836 /*
2837 * common parseDate handler for parseDate, parseJulianDate
2838 */
2839 int CVmObjDate::common_parseDate(VMG_ vm_val_t *retval, uint *oargc,
2840 multicaldate_t *cal)
2841 {
2842 /* check arguments */
2843 uint argc = (oargc != 0 ? *oargc : 0);
2844 static CVmNativeCodeDesc desc(1, 3, FALSE);
2845 if (get_prop_check_argc(retval, oargc, &desc))
2846 return TRUE;
2847
2848 /* set up a locale state interface */
2849 CVmDateLocale lc Pvmg0_P;
2850
2851 /* retrieve the string to parse */
2852 const char *src = G_stk->get(0)->get_as_string(vmg0_);
2853 if (src == 0)
2854 err_throw(VMERR_BAD_VAL_BIF);
2855
2856 /* retrieve the format string/list argument, if present */
2857 const vm_val_t *custom = 0;
2858 if (argc >= 2 && G_stk->get(1)->typ != VM_NIL)
2859 custom = G_stk->get(1);
2860
2861 /* retrieve the reference date, if present */
2862 int32_t refday, reftime;
2863 if (argc >= 3 && G_stk->get(2)->typ != VM_NIL)
2864 {
2865 /* get the reference date */
2866 CVmObjDate *refdate = vm_val_cast(CVmObjDate, G_stk->get(2));
2867 if (refdate == 0)
2868 err_throw(VMERR_BAD_TYPE_BIF);
2869
2870 /* get its contents */
2871 refday = refdate->get_ext()->dayno;
2872 reftime = refdate->get_ext()->daytime;
2873 }
2874 else
2875 {
2876 /* no reference date argument - get the current date and time */
2877 caldate_t::now(refday, reftime);
2878 }
2879
2880 /* retrieve the reference time zone, if present */
2881 CVmTimeZone *reftz = get_tz_arg(vmg_ 3, argc);
2882
2883 /* parse the date */
2884 int32_t dayno, daytime;
2885 date_parse_result result(cal);
2886 date_parse_string fmt_match[20];
2887 int fmt_match_cnt = countof(fmt_match);
2888 if (parse_date_string(vmg_ dayno, daytime, src, custom, &lc,
2889 cal, refday, reftime, reftz, &result,
2890 fmt_match, &fmt_match_cnt))
2891 {
2892 /* create the return list */
2893 retval->set_obj(CVmObjList::create(vmg_ FALSE, 5));
2894 G_stk->push(retval);
2895 CVmObjList *lst = (CVmObjList *)vm_objp(vmg_ retval->val.obj);
2896 lst->cons_clear();
2897
2898 /* element [1] is the return date */
2899 vm_val_t ele;
2900 ele.set_obj(CVmObjDate::create(vmg_ FALSE, dayno, daytime));
2901 lst->cons_set_element(0, &ele);
2902
2903 /* [2] is the TimeZone object, if applicable */
2904 ele.set_nil();
2905 if (result.tz != reftz)
2906 ele.set_obj(CVmObjTimeZone::create(vmg_ result.tz));
2907 lst->cons_set_element(1, &ele);
2908
2909 /* [3] is the fixed timezone offset in seconds, if applicable */
2910 ele.set_nil();
2911 if (result.has_tzofs())
2912 ele.set_int(result.tzofs / 1000);
2913 lst->cons_set_element(2, &ele);
2914
2915 /* [4] next is the format string matched */
2916 ele.set_obj(CVmObjList::create(vmg_ FALSE, fmt_match_cnt));
2917 lst->cons_set_element(3, &ele);
2918 CVmObjList *flst = (CVmObjList *)vm_objp(vmg_ ele.val.obj);
2919 flst->cons_clear();
2920
2921 /* populate the format string list */
2922 for (int fi = 0 ; fi < fmt_match_cnt ; ++fi)
2923 enlist_str(vmg_ flst, fi, fmt_match[fi]);
2924
2925 /* [5] is a sublist with the source substrings */
2926 ele.set_obj(CVmObjList::create(vmg_ FALSE, 13));
2927 lst->cons_set_element(4, &ele);
2928 CVmObjList *slst = (CVmObjList *)vm_objp(vmg_ ele.val.obj);
2929 slst->cons_clear();
2930
2931 /* now add the date component source strings */
2932 enlist_str(vmg_ slst, 0, result.pera);
2933 enlist_str(vmg_ slst, 1, result.pyy);
2934 enlist_str(vmg_ slst, 2, result.pmm);
2935 enlist_str(vmg_ slst, 3, result.pdd);
2936 enlist_str(vmg_ slst, 4, result.pdoy);
2937 enlist_str(vmg_ slst, 5, result.pw);
2938 enlist_str(vmg_ slst, 6, result.pampm);
2939 enlist_str(vmg_ slst, 7, result.phh);
2940 enlist_str(vmg_ slst, 8, result.pmi);
2941 enlist_str(vmg_ slst, 9, result.pss);
2942 enlist_str(vmg_ slst, 10, result.pms);
2943 enlist_str(vmg_ slst, 11, result.punix);
2944 enlist_str(vmg_ slst, 12, result.ptz);
2945
2946 /* done with the list gc protection */
2947 G_stk->discard();
2948 }
2949 else
2950 {
2951 /* return nil */
2952 retval->set_nil();
2953 }
2954
2955 /* discard arguments */
2956 G_stk->discard(argc);
2957
2958 /* handled */
2959 return TRUE;
2960 }
2961
2962
2963 /* ------------------------------------------------------------------------ */
2964 /*
2965 * formatDate method
2966 */
2967 int CVmObjDate::getp_formatDate(VMG_ vm_obj_id_t self,
2968 vm_val_t *retval, uint *oargc)
2969 {
2970 gregcaldate_t cd;
2971 return formatDateGen(vmg_ self, retval, oargc, &cd);
2972 }
2973
2974 /*
2975 * formatJulianDate method
2976 */
2977 int CVmObjDate::getp_formatJulianDate(VMG_ vm_obj_id_t self,
2978 vm_val_t *retval, uint *oargc)
2979 {
2980 julcaldate_t cd;
2981 return formatDateGen(vmg_ self, retval, oargc, &cd);
2982 }
2983
2984 /*
2985 * general date formatter
2986 */
2987 int CVmObjDate::formatDateGen(VMG_ vm_obj_id_t self, vm_val_t *retval,
2988 uint *oargc, multicaldate_t *date)
2989 {
2990 /* check arguments */
2991 uint argc = (oargc != 0 ? *oargc : 0);
2992 static CVmNativeCodeDesc desc(1, 1);
2993 if (get_prop_check_argc(retval, oargc, &desc))
2994 return TRUE;
2995
2996 /* get the format string */
2997 const char *fmt = G_stk->get(0)->get_as_string(vmg0_);
2998 if (fmt == 0)
2999 err_throw(VMERR_BAD_TYPE_BIF);
3000
3001 /* get the format string length and buffer pointer */
3002 size_t fmtlen = vmb_get_len(fmt);
3003 fmt += VMB_LEN;
3004
3005 /* get my date and time in local time */
3006 CVmTimeZone *tz = get_tz_arg(vmg_ 1, argc);
3007 int32_t dayno, daytime, tzofs;
3008 const char *tzabbr = get_local_time(dayno, daytime, tzofs, tz);
3009
3010 /* convert the day number to a calendar date */
3011 date->set_dayno(dayno);
3012
3013 /* do a formatting pass to determine how much space we need */
3014 CVmDateLocale lc Pvmg0_P;
3015 size_t buflen = format_date(
3016 vmg_ 0, 0, fmt, fmtlen, &lc, date, dayno, daytime, tzabbr, tzofs);
3017
3018 /* create a string for the result */
3019 retval->set_obj(CVmObjString::create(vmg_ FALSE, buflen));
3020 CVmObjString *str = vm_objid_cast(CVmObjString, retval->val.obj);
3021
3022 /* format the string into the buffer */
3023 format_date(vmg_ str->cons_get_buf(), buflen, fmt, fmtlen, &lc,
3024 date, dayno, daytime, tzabbr, tzofs);
3025
3026 /* discard arguments */
3027 G_stk->discard(argc);
3028
3029 /* handled */
3030 return TRUE;
3031 }
3032
3033 /* macro: write a character to the output buffer if there's room */
3034 #define wrtch(ch) (++outlen, buflen > 0 ? *buf++ = ch, --buflen : 0)
3035
3036 /* macros: write a null-terminated/counted length string */
3037 #define wrtstr(str) wrtstrl(str, strlen(str))
3038 #define wrttstr(str) wrtstrl(str + VMB_LEN, vmb_get_len(str))
3039 #define wrtstrl(str, len) _wrtstrl(buf, buflen, outlen, str, len)
3040
3041 /* service routine: write a counted-length string */
3042 static void _wrtstrl(char *&buf, size_t &buflen, size_t &outlen,
3043 const char *str, size_t len)
3044 {
3045 /* if it fits, copy the whole thing; otherwise copy as much as fits */
3046 if (len <= buflen)
3047 {
3048 memcpy(buf, str, len);
3049 buf += len;
3050 buflen -= len;
3051 }
3052 else if (buflen != 0)
3053 {
3054 memcpy(buf, str, buflen);
3055 buf += buflen;
3056 buflen = 0;
3057 }
3058
3059 /* count it all in the output */
3060 outlen += len;
3061 }
3062
3063 /* macro: write an n-digit number */
3064 #define wrtnum(v, ndigits) \
3065 _wrtnum(buf, buflen, outlen, v, ndigits, pound, leadsp, roman)
3066
3067 /* service routine: write an n-digit number */
3068 static void _wrtnum(char *&buf, size_t &buflen, size_t &outlen,
3069 int v, int ndigits, int pound, char leadsp, int roman)
3070 {
3071 char numbuf[20];
3072 int i = 0;
3073 int neg = FALSE;
3074
3075 /* note the sign */
3076 if (v < 0)
3077 {
3078 wrtch('-');
3079 v = -v;
3080 neg = TRUE;
3081 }
3082
3083 /* if desired, generate a Roman numeral, if it's in range (1-4999) */
3084 if (roman && !neg && v >= 1 && v <= 4999)
3085 {
3086 static const struct
3087 {
3088 const char *r;
3089 int val;
3090 } r[] = {
3091 { "M", 1000 },
3092 { "CM", 900 },
3093 { "D", 500 },
3094 { "CD", 400 },
3095 { "C", 100 },
3096 { "XC", 90 },
3097 { "L", 50 },
3098 { "X", 10 },
3099 { "IX", 9 },
3100 { "V", 5 },
3101 { "IV", 4 },
3102 { "I", 1 }
3103 };
3104 for (int i = 0 ; v != 0 && i < countof(r) ; )
3105 {
3106 /* if this numeral fits, append it */
3107 if (r[i].val <= v)
3108 {
3109 /* it fits - write it and deduct it from the balance */
3110 wrtstr(r[i].r);
3111 v -= r[i].val;
3112 }
3113 else
3114 {
3115 /* doesn't fit - move on to the next lower numeral */
3116 ++i;
3117 }
3118 }
3119 return;
3120 }
3121
3122 /* generate digits */
3123 do {
3124 div_t q = div(v, 10);
3125 v = q.quot;
3126 numbuf[i++] = '0' + q.rem;
3127 } while (v != 0);
3128
3129 /*
3130 * if we didn't generate as many digits as the field requires, add
3131 * leading zeros or spaces, as desired
3132 */
3133 if (i < ndigits && (leadsp != 0 || !pound))
3134 {
3135 /* add leading digits or the specified spaces */
3136 char lead = leadsp != 0 ? leadsp : '0';
3137 for (int j = i ; j < ndigits ; ++j)
3138 wrtch(lead);
3139 }
3140
3141 /* write the digits */
3142 for ( ; i > 0 ; --i, wrtch(numbuf[i])) ;
3143 }
3144
3145 /* write a locale string list item */
3146 #define wrtlistitem(item, idx, sticky) \
3147 _wrtlistitem(vmg_ buf, buflen, outlen, lc, item, idx, sticky)
3148 static void _wrtlistitem(VMG_ char *&buf, size_t &buflen, size_t &outlen,
3149 CVmDateLocale *lc, int item, int idx, int sticky)
3150 {
3151 /* get the list item */
3152 size_t len;
3153 const char *str = lc->index_list(vmg_ len, item, idx, sticky);
3154
3155 /* write the item */
3156 for ( ; len != 0 ; ++str, --len)
3157 wrtch(*str);
3158 }
3159
3160 /*
3161 * Internal date formatter. Formats into a buffer; if no buffer is
3162 * provided, counts the length required. Note that the date is specified
3163 * in the *local* time zone - the caller must adjust to local time before
3164 * calling. Null-terminates the result if there's room, but doesn't
3165 * include the null terminator in the size count.
3166 *
3167 * Most of our format codes are the same as for C/C++/php strftime, which
3168 * are mostly the same as MySQL DATE_FORMAT(). We support all of the
3169 * strftime formats, with the same letter codes, except for the php tab
3170 * (%t) and newline (%n), which I don't see any good reason to include when
3171 * we could just as well use \t and \n. We support all of the MySQL format
3172 * options, although several have different codes (MySQL mostly follows the
3173 * strftime codes, though).
3174 */
3175 size_t CVmObjDate::format_date(VMG_ char *buf, size_t buflen,
3176 const char *fmt, size_t fmtlen,
3177 CVmDateLocale *lc,
3178 const multicaldate_t *date,
3179 int32_t dayno, int32_t daytime,
3180 const char *tzabbr, int32_t tzofs) const
3181 {
3182 const char *subfmt;
3183 size_t subfmtl;
3184
3185 /* we haven't written anything to the buffer yet */
3186 size_t outlen = 0;
3187
3188 /* scan the format string */
3189 for ( ; fmtlen != 0 ; ++fmt, --fmtlen)
3190 {
3191 if (*fmt == '%' && fmtlen >= 2)
3192 {
3193 /* skip the '%' */
3194 ++fmt, --fmtlen;
3195
3196 /* parse flags */
3197 int pound = FALSE;
3198 int minus = FALSE;
3199 int roman = FALSE;
3200 char leadsp = 0;
3201 for (int found_flag = TRUE ; found_flag && fmtlen >= 2 ; )
3202 {
3203 /* assume we won't find another flag on this pass */
3204 found_flag = FALSE;
3205
3206 /* check for the '#' flag (meaning varies by format code) */
3207 if (fmtlen >= 2 && *fmt == '#')
3208 {
3209 pound = found_flag = TRUE;
3210 ++fmt, --fmtlen;
3211 }
3212
3213 /* ' ' and '\ ' (replace leading zeros with spaces) */
3214 if (fmtlen >= 2 && (*fmt == ' ' || *fmt == 0x15))
3215 {
3216 leadsp = *fmt;
3217 found_flag = TRUE;
3218 ++fmt, --fmtlen;
3219 }
3220
3221 /* check for '-' flag */
3222 if (fmtlen >= 2 && *fmt == '-')
3223 {
3224 minus = found_flag = TRUE;
3225 ++fmt, --fmtlen;
3226 }
3227
3228 /* check for '&' flag */
3229 if (fmtlen >= 2 && *fmt == '&')
3230 {
3231 roman = found_flag = TRUE;
3232 ++fmt, --fmtlen;
3233 }
3234 }
3235
3236 /* get the format code */
3237 switch (*fmt)
3238 {
3239 case 'a':
3240 /* abbreviated day name */
3241 wrtlistitem(LC_WKDY, date->weekday(), FALSE);
3242 break;
3243
3244 case 'A':
3245 /* full day name */
3246 wrtlistitem(LC_WEEKDAY, date->weekday(), FALSE);
3247 break;
3248
3249 case 'd':
3250 /* two-digit day of month (or one digit with '#') */
3251 wrtnum(date->d(), 2);
3252 break;
3253
3254 case 'j':
3255 /* day of year 001-366, three digits with leading zeros */
3256 {
3257 /*
3258 * we can calculate the day of the year by subtracting
3259 * the day number of Jan 1 from the given date (and
3260 * adding 1 to get into range 1-366)
3261 */
3262 caldate_t jan1(date->y(), 1, 1);
3263 int j = dayno - jan1.dayno() + 1;
3264 wrtnum(j, 3);
3265 }
3266 break;
3267
3268 case 'J':
3269 /*
3270 * Julian day number (the 4713 BC kind); '#' suppresses the
3271 * fractional part
3272 */
3273 {
3274 /* get the day and time */
3275 long dn = get_dayno(), dt = get_daytime();
3276
3277 /* if the time is past noon, it's on the next day */
3278 if (dt > 12*60*60*1000)
3279 dn += 1, dt -= 12*60*60*1000;
3280
3281 /*
3282 * figure the combined date/time value, adjusting the
3283 * day number to the Julian day Epoch
3284 */
3285 bignum_t<32> bdn(dn), bdt(dt);
3286 bdn += 1721119L;
3287 bdn += (bdt / (long)(24*60*60*1000));
3288
3289 /* format it and write it */
3290 char jbuf[64];
3291 bdn.format(jbuf, sizeof(jbuf), -1, 10);
3292 wrttstr(jbuf);
3293 }
3294 break;
3295
3296 case 'u':
3297 /* day of week 1-7 Monday-Sunday (ISO weekday) */
3298 wrtnum(date->iso_weekday(), 1);
3299 break;
3300
3301 case 'w':
3302 /* day of week 0-6 Sunday-Saturday */
3303 wrtnum(date->weekday(), 1);
3304 break;
3305
3306 case 't':
3307 /* day of month with ordinal suffix (non-strftime) */
3308 wrtnum(date->d(), 1);
3309 wrtlistitem(LC_ORDSUF, ordinal_index(date->d()), TRUE);
3310 break;
3311
3312 case 'U':
3313 /* week number, 00-53, week 1 starting with first Sunday */
3314 wrtnum(date->weekno(0), 2);
3315 break;
3316
3317 case 'W':
3318 /* week number, 00-53, week 1 starting with first Monday */
3319 wrtnum(date->weekno(1), 2);
3320 break;
3321
3322 case 'V':
3323 /* ISO-8601:1988 week number of the year */
3324 wrtnum(date->iso_weekno(0), 2);
3325 break;
3326
3327 case 'b':
3328 /* abbreviated month name */
3329 wrtlistitem(LC_MON, date->m() - 1, FALSE);
3330 break;
3331
3332 case 'B':
3333 /* full month name */
3334 wrtlistitem(LC_MONTH, date->m() - 1, FALSE);
3335 break;
3336
3337 case 'm':
3338 /* two-digit month 01-12 (one digit with #) */
3339 wrtnum(date->m(), 2);
3340 break;
3341
3342 case 'C':
3343 /* two-digit century (e.g., 19 for 1900-1999) */
3344 wrtnum(date->y() / 100, 2);
3345 break;
3346
3347 case 'g':
3348 case 'G':
3349 /* ISO-8601:1988 year ('g'=2 digits, 'G'=4 digits) */
3350 {
3351 /* ISO-8601:1988 week number of the year */
3352 int iy;
3353 date->iso_weekno(&iy);
3354 wrtnum(iy, *fmt == 'g' ? 2 : 4);
3355 }
3356 break;
3357
3358 case 'y':
3359 /* two-digit year */
3360 wrtnum(ldiv(date->y(), 100).rem, 2);
3361 break;
3362
3363 case 'Y':
3364 /* four-digit year */
3365 wrtnum(date->y(), 4);
3366 break;
3367
3368 case 'e':
3369 case 'E':
3370 /*
3371 * Year with AD/BC era before/after the year number. For
3372 * 'e', the era is always after, or always before on '-'.
3373 * For 'E', the era is AD before/BC after, or reversed on
3374 * '-'.
3375 */
3376 {
3377 /* figure the era: positive years are AD, <=0 are BC */
3378 int idx = 0; // assume AD
3379 int yy = date->y();
3380 if (yy <= 0)
3381 {
3382 idx = 1; // BC
3383 yy = -yy + 1;
3384 }
3385
3386 /*
3387 * Figure the display order: "%-e" puts the era first
3388 * in all case; "%E" puts AD first; "%-E" puts BC first
3389 */
3390 if ((*fmt == 'e' && minus)
3391 || (*fmt == 'E' && !minus && idx == 0)
3392 || (*fmt == 'E' && minus && idx == 1))
3393 {
3394 /* era first */
3395 wrtlistitem(LC_ERA, idx, FALSE);
3396 wrtch(' ');
3397 wrtnum(yy, 1);
3398 }
3399 else
3400 {
3401 /* year first */
3402 wrtnum(yy, 1);
3403 wrtch(' ');
3404 wrtlistitem(LC_ERA, idx, FALSE);
3405 }
3406 }
3407 break;
3408
3409 case 'H':
3410 /* two-digit hour, 24-hour clock */
3411 wrtnum(daytime/(60*60*1000), 2);
3412 break;
3413
3414 case 'I':
3415 /* two-digit hour, 12-hour clock */
3416 {
3417 int hh = daytime/(60*60*1000);
3418 if (hh == 0)
3419 hh = 12;
3420 else if (hh >= 13)
3421 hh -= 12;
3422
3423 wrtnum(hh, 2);
3424 }
3425 break;
3426
3427 case 'M':
3428 /* two-digit minute */
3429 wrtnum(daytime/(60*1000) % 60, 2);
3430 break;
3431
3432 case 'P':
3433 /* upper-case AM or PM */
3434 wrtlistitem(LC_AMPM, daytime/(60*60*1000) >= 12 ? 1 : 0, FALSE);
3435 break;
3436
3437 case 'p':
3438 /* lower-case am or pm */
3439 wrtlistitem(LC_AMPM, daytime/(60*60*1000) >= 12 ? 3 : 2, FALSE);
3440 break;
3441
3442 case 'r':
3443 /* full 12-hour clock time: %I:%M:%S %P */
3444 subfmt = lc->get(vmg_ subfmtl, LC_FMT_12HOUR);
3445 goto do_subfmt;
3446
3447 do_subfmt:
3448 {
3449 /* recursively format the new format string */
3450 size_t l = format_date(
3451 vmg_ buf, buflen, subfmt, subfmtl, lc,
3452 date, dayno, daytime, tzabbr, tzofs);
3453
3454 /* count it in our output length */
3455 outlen += l;
3456
3457 /* advance our buffer pointer past the copied text */
3458 if (buflen >= l)
3459 buflen -= l, buf += l;
3460 else
3461 buf += buflen, buflen = 0;
3462 }
3463 break;
3464
3465 case 'R':
3466 /* 24-hour clock time w/minutes: %H:%M */
3467 subfmt = lc->get(vmg_ subfmtl, LC_FMT_24HOUR);
3468 goto do_subfmt;
3469
3470 case 'S':
3471 /* two-digit seconds */
3472 wrtnum(daytime/1000 % 60, 2);
3473 break;
3474
3475 case 'N':
3476 /* three-digit milliseconds (non-strftime) */
3477 wrtnum(daytime % 1000, 3);
3478 break;
3479
3480 case 'T':
3481 /* 24-hour clock time w/seconds: %H:%M:%S */
3482 subfmt = lc->get(vmg_ subfmtl, LC_FMT_24HOURSECS);
3483 goto do_subfmt;
3484
3485 case 'X':
3486 /* locale time representation without the date */
3487 subfmt = lc->get(vmg_ subfmtl, LC_FMT_TIME);
3488 goto do_subfmt;
3489
3490 case 'z':
3491 /* time zone abbreviation */
3492 {
3493 for (const char *p = tzabbr ; *p != '\0' ; ++p)
3494 wrtch(*p);
3495 }
3496 break;
3497
3498 case 'Z':
3499 /* time zone UTC offset, four digits (+0500) */
3500 {
3501 int32_t o = tzofs;
3502 if (o < 0)
3503 wrtch('-'), o = -o;
3504 else
3505 wrtch('+');
3506
3507 wrtnum(o/(60*60*1000), 2);
3508 pound = FALSE;
3509 wrtnum(o/(60*1000) % 60, 2);
3510 }
3511 break;
3512
3513 case 'c':
3514 /* preferred locale date and time stamp */
3515 subfmt = lc->get(vmg_ subfmtl, LC_FMT_TIMESTAMP);
3516 goto do_subfmt;
3517
3518 case 'D':
3519 /* short date - %m/%d/%y */
3520 subfmt = lc->get(vmg_ subfmtl, LC_FMT_SHORTDATE);
3521 goto do_subfmt;
3522
3523 case 'F':
3524 /* database-style date: %Y-%m-%d */
3525 subfmt = "%Y-%m-%d";
3526 subfmtl = 8;
3527 goto do_subfmt;
3528
3529 case 's':
3530 /* Unix Epoch timestamp as an integer */
3531 {
3532 /*
3533 * The Unix timestamp is the number of seconds after
3534 * (or before, if negative) 1/1/1970 00:00 UTC. First
3535 * calculate the number of days after (before) 1/1/1970
3536 * by subtracting the Unix Epoch day number from our
3537 * internal day number; then multiply that by the
3538 * number of seconds in a day (24*60*60) to get the
3539 * Unix timestamp of midnight on that day, then add the
3540 * number of seconds into the day ('daytime' stores
3541 * milliseconds, so divide it by 1000).
3542 *
3543 * Note that we need to adjust back to UTC by
3544 * subtracting the time zone offset.
3545 *
3546 * As we've discussed elsewhere in this file, a double
3547 * is big enough for the Unix timestamp value for any
3548 * day number we can store, and represents it exactly
3549 * since we're working in whole numbers.
3550 */
3551 double utime = (dayno - caldate_t::UNIX_EPOCH_DAYNO)
3552 * 24.*60.*60.
3553 + daytime/1000
3554 - tzofs/1000;
3555
3556 /* format it to a buffer and copy to the output */
3557 char ubuf[60];
3558 sprintf(ubuf, "%.0lf", utime);
3559 wrtstr(ubuf);
3560 }
3561 break;
3562
3563 case 'x':
3564 /* preferred locale date representation */
3565 subfmt = lc->get(vmg_ subfmtl, LC_FMT_DATE);
3566 goto do_subfmt;
3567
3568 case '%':
3569 /* a literal % */
3570 wrtch('%');
3571 break;
3572
3573 default:
3574 /*
3575 * anything else is an error; copy the whole %x literally
3576 * to make the unparsed format character apparent
3577 */
3578 wrtch('%');
3579 wrtch(*fmt);
3580 break;
3581 }
3582 }
3583 else
3584 {
3585 /* it's an ordinary character, so copy it literally */
3586 wrtch(*fmt);
3587 }
3588 }
3589
3590 /* add a nul if there's room (but don't count it in the result length) */
3591 if (buflen > 0)
3592 *buf++ = '\0';
3593
3594 /* return the total space needed */
3595 return outlen;
3596 }
3597
3598 /* done with our local macros */
3599 #undef wrtch
3600 #undef wrt2dig
3601
3602
3603 /* ------------------------------------------------------------------------ */
3604 /*
3605 * compareTo method
3606 */
3607 int CVmObjDate::getp_compareTo(VMG_ vm_obj_id_t self,
3608 vm_val_t *retval, uint *oargc)
3609 {
3610 /* check arguments */
3611 uint argc = (oargc != 0 ? *oargc : 0);
3612 static CVmNativeCodeDesc desc(1);
3613 if (get_prop_check_argc(retval, oargc, &desc))
3614 return TRUE;
3615
3616 /* get the other date */
3617 CVmObjDate *other = vm_val_cast(CVmObjDate, G_stk->get(0));
3618 if (other == 0)
3619 err_throw(VMERR_BAD_TYPE_BIF);
3620
3621 /* get the respective dates */
3622 int32_t dayno = get_ext()->dayno;
3623 int32_t daytime = get_ext()->daytime;
3624 int32_t odayno = other->get_ext()->dayno;
3625 int32_t odaytime = other->get_ext()->daytime;
3626
3627 /* do the comparison */
3628 retval->set_int(dayno != odayno ? dayno - odayno : daytime - odaytime);
3629
3630 /* discard arguments */
3631 G_stk->discard(argc);
3632
3633 /* handled */
3634 return TRUE;
3635 }
3636
3637 /* ------------------------------------------------------------------------ */
3638 /*
3639 * getDate method
3640 */
3641 int CVmObjDate::getp_getDate(VMG_ vm_obj_id_t self,
3642 vm_val_t *retval, uint *oargc)
3643 {
3644 /* check arguments */
3645 uint argc = (oargc != 0 ? *oargc : 0);
3646 static CVmNativeCodeDesc desc(0, 1);
3647 if (get_prop_check_argc(retval, oargc, &desc))
3648 return TRUE;
3649
3650 /* get my date in local time */
3651 int32_t dayno = get_local_date(get_tz_arg(vmg_ 0, argc));
3652
3653 /* express it as a calendar date */
3654 caldate_t cd(dayno);
3655
3656 /* return [year, month, monthday, weekday] */
3657 make_int_list(vmg_ retval, 4, cd.y, cd.m, cd.d, cd.weekday() + 1);
3658
3659 /* discard arguments */
3660 G_stk->discard(argc);
3661
3662 /* handled */
3663 return TRUE;
3664 }
3665
3666 /* ------------------------------------------------------------------------ */
3667 /*
3668 * getJulianDay method
3669 */
3670 int CVmObjDate::getp_getJulianDay(VMG_ vm_obj_id_t self,
3671 vm_val_t *retval, uint *oargc)
3672 {
3673 /* check arguments */
3674 uint argc = (oargc != 0 ? *oargc : 0);
3675 static CVmNativeCodeDesc desc(0);
3676 if (get_prop_check_argc(retval, oargc, &desc))
3677 return TRUE;
3678
3679 /* get the Julian day number for midnight UTC on my day number */
3680 caldate_t cd(get_ext()->dayno);
3681 bignum_t<32> jday(cd.julian_dayno());
3682
3683 /* add my fraction of a day past midnight UTC */
3684 bignum_t<32> jt((long)get_ext()->daytime);
3685 jday += jt / (long)(24*60*60*1000);
3686
3687 /* return a BigNumber result */
3688 retval->set_obj(CVmObjBigNum::create(vmg_ FALSE, &jday));
3689
3690 /* discard arguments */
3691 G_stk->discard(argc);
3692
3693 /* handled */
3694 return TRUE;
3695 }
3696
3697 /* ------------------------------------------------------------------------ */
3698 /*
3699 * getJulianDate method
3700 */
3701 int CVmObjDate::getp_getJulianDate(VMG_ vm_obj_id_t self,
3702 vm_val_t *retval, uint *oargc)
3703 {
3704 /* check arguments */
3705 uint argc = (oargc != 0 ? *oargc : 0);
3706 static CVmNativeCodeDesc desc(0, 1);
3707 if (get_prop_check_argc(retval, oargc, &desc))
3708 return TRUE;
3709
3710 /* get my date in local time */
3711 int32_t dayno = get_local_date(get_tz_arg(vmg_ 0, argc));
3712
3713 /* get the julian date */
3714 caldate_t cd(dayno);
3715 int y, m, d;
3716 cd.julian_date(y, m, d);
3717
3718 /*
3719 * Return [year, month, monthday, weekday]. Note that there's no
3720 * separate Julian weekday calculation, since the Julian calendar and
3721 * Gregorian agree on the day of the week for every day.
3722 */
3723 make_int_list(vmg_ retval, 4, y, m, d, cd.weekday() + 1);
3724
3725 /* discard arguments */
3726 G_stk->discard(argc);
3727
3728 /* handled */
3729 return TRUE;
3730 }
3731
3732 /* ------------------------------------------------------------------------ */
3733 /*
3734 * getISOWeekDate method
3735 */
3736 int CVmObjDate::getp_getISOWeekDate(VMG_ vm_obj_id_t self,
3737 vm_val_t *retval, uint *oargc)
3738 {
3739 /* check arguments */
3740 uint argc = (oargc != 0 ? *oargc : 0);
3741 static CVmNativeCodeDesc desc(0, 1);
3742 if (get_prop_check_argc(retval, oargc, &desc))
3743 return TRUE;
3744
3745 /* get my date in local time */
3746 int32_t dayno = get_local_date(get_tz_arg(vmg_ 0, argc));
3747
3748 /* express it as a calendar date */
3749 caldate_t cd(dayno);
3750
3751 /* return [iso year, iso week, iso day] */
3752 int iy;
3753 int iw = cd.iso_weekno(&iy);
3754 make_int_list(vmg_ retval, 3, iy, iw, cd.iso_weekday());
3755
3756 /* discard arguments */
3757 G_stk->discard(argc);
3758
3759 /* handled */
3760 return TRUE;
3761 }
3762
3763 /* ------------------------------------------------------------------------ */
3764 /*
3765 * getTime method
3766 */
3767 int CVmObjDate::getp_getTime(VMG_ vm_obj_id_t self,
3768 vm_val_t *retval, uint *oargc)
3769 {
3770 /* check arguments */
3771 uint argc = (oargc != 0 ? *oargc : 0);
3772 static CVmNativeCodeDesc desc(0, 1);
3773 if (get_prop_check_argc(retval, oargc, &desc))
3774 return TRUE;
3775
3776 /* get my date and time in local time */
3777 int32_t dayno, daytime;
3778 get_local_time(dayno, daytime, get_tz_arg(vmg_ 0, argc));
3779
3780 /* return [hour, minute, second, msec] */
3781 make_int_list(vmg_ retval, 4,
3782 daytime/(24*60*60*1000),
3783 daytime/(60*60*1000) % 60,
3784 daytime/(60*1000) % 60,
3785 daytime % 1000);
3786
3787 /* discard arguments */
3788 G_stk->discard(argc);
3789
3790 /* handled */
3791 return TRUE;
3792 }
3793
3794 /* ------------------------------------------------------------------------ */
3795 /*
3796 * addInterval method
3797 */
3798 int CVmObjDate::getp_addInterval(VMG_ vm_obj_id_t self,
3799 vm_val_t *retval, uint *oargc)
3800 {
3801 /* check arguments */
3802 uint argc = (oargc != 0 ? *oargc : 0);
3803 static CVmNativeCodeDesc desc(1);
3804 if (get_prop_check_argc(retval, oargc, &desc))
3805 return TRUE;
3806
3807 /* get the interval list */
3808 vm_val_t *lst = G_stk->get(0);
3809 if (!lst->is_listlike(vmg0_))
3810 err_throw(VMERR_BAD_TYPE_BIF);
3811
3812 /* retrieve my date as a calendar object */
3813 int32_t dayno = get_ext()->dayno;
3814 caldate_t cd(dayno);
3815
3816 /* retrieve my time as a double, to allow for overflows from int32 */
3817 double daytime = get_ext()->daytime;
3818
3819 /* add each element from the list */
3820 int cnt = lst->ll_length(vmg0_);
3821 for (int i = 1 ; i <= cnt ; ++i)
3822 {
3823 /* get this interval element */
3824 vm_val_t ele;
3825 lst->ll_index(vmg_ &ele, i);
3826
3827 /* treat nil as zero */
3828 if (ele.typ == VM_NIL)
3829 continue;
3830
3831 /* add it to the appropriate date or time component */
3832 switch (i)
3833 {
3834 case 1: cd.y += ele.num_to_int(vmg0_); break;
3835 case 2: cd.m += ele.num_to_int(vmg0_); break;
3836 case 3: cd.d += ele.num_to_int(vmg0_); break;
3837
3838 case 4: daytime += ele.num_to_double(vmg0_)*60.*60.*1000.; break;
3839 case 5: daytime += ele.num_to_double(vmg0_)*60.*1000.; break;
3840 case 6: daytime += ele.num_to_double(vmg0_)*1000.; break;
3841 }
3842 }
3843
3844 /* carry overflows from the time into the day */
3845 double day_carry = floor(daytime / (24.*60.*60.*1000.));
3846 daytime -= day_carry * (24.*60.*60.*1000.);
3847
3848 if (day_carry + cd.d > INT32MAXVAL || day_carry + cd.d < INT32MINVAL)
3849 err_throw(VMERR_NUM_OVERFLOW);
3850
3851 cd.d += (int32_t)day_carry;
3852
3853 /* return the new date, using our same local timezone */
3854 retval->set_obj(create(vmg_ FALSE, cd.dayno(), (int32_t)daytime));
3855
3856 /* discard arguments */
3857 G_stk->discard(argc);
3858
3859 /* handled */
3860 return TRUE;
3861 }
3862
3863
3864 /* ------------------------------------------------------------------------ */
3865 /*
3866 * findWeekday method
3867 */
3868 int CVmObjDate::getp_findWeekday(VMG_ vm_obj_id_t self,
3869 vm_val_t *retval, uint *oargc)
3870 {
3871 /* check arguments */
3872 uint argc = (oargc != 0 ? *oargc : 0);
3873 static CVmNativeCodeDesc desc(2, 1);
3874 if (get_prop_check_argc(retval, oargc, &desc))
3875 return TRUE;
3876
3877 /* get the day of week and 'which' arguments */
3878 int32_t wday = G_stk->get(0)->num_to_int(vmg0_);
3879 int32_t which = G_stk->get(1)->num_to_int(vmg0_);
3880
3881 /* check the weekday and 'which' ranges */
3882 if (wday < 1 || wday > 7 || which == 0)
3883 err_throw(VMERR_BAD_VAL_BIF);
3884
3885 /* adjust wday to 0=Sunday */
3886 wday -= 1;
3887
3888 /* get my date in local time */
3889 CVmTimeZone *tz = get_tz_arg(vmg_ 2, argc);
3890 int32_t dayno = get_local_date(tz);
3891
3892 /* figure my weekday */
3893 caldate_t cd(dayno);
3894 int my_wday = cd.weekday();
3895
3896 /* figure the difference between the target day and my day, mod 7 */
3897 int delta = (7 + wday - my_wday) % 7;
3898
3899 /*
3900 * Go forward that many days, or backwards (7 - delta), to get the
3901 * first occurrence before/after my date. Then go forwards or
3902 * backwards by additional weeks as needed.
3903 */
3904 if (which > 0)
3905 dayno += delta + (which-1)*7;
3906 else
3907 dayno -= ((7 - delta) % 7) + (-which-1)*7;
3908
3909 /* return a new date at midnight on the given day */
3910 int32_t daytime = 0;
3911 tz->local_to_utc(dayno, daytime);
3912 retval->set_obj(create(vmg_ FALSE, dayno, daytime));
3913
3914 /* discard arguments */
3915 G_stk->discard(argc);
3916
3917 /* handled */
3918 return TRUE;
3919 }
3920
3921 /* ------------------------------------------------------------------------ */
3922 /*
3923 * Get a TimeZone argument. If the argument is nil or omitted, we'll
3924 * return the default local system TimeZone object. If it's a TimeZone
3925 * object, we'll return that as given. If it's a string or integer, we'll
3926 * construct a TimeZone object using that value per the TimeZone
3927 * constructors.
3928 *
3929 * 'argn' is the argument number to fetch; 'argc' is the actual number of
3930 * arguments passed to the method.
3931 */
3932 CVmTimeZone *CVmObjDate::get_tz_arg(VMG_ uint argn, uint argc)
3933 {
3934 /* if the argument is nil or missing, use the default local zone */
3935 vm_val_t *argp = G_stk->get(argn);
3936 if (argn == argc || argp->typ == VM_NIL)
3937 return G_tzcache->get_local_zone(vmg0_);
3938
3939 /* check for a TimeZone object */
3940 CVmObjTimeZone *tzobj;
3941 if (argn < argc && (tzobj = vm_val_cast(CVmObjTimeZone, argp)) != 0)
3942 return tzobj->get_tz();
3943
3944 /* otherwise, accept anything that the TimeZone constructor accepts */
3945 return CVmObjTimeZone::parse_ctor_args(vmg_ argp, argc - argn);
3946 }
3947
3948 /* ------------------------------------------------------------------------ */
3949 /*
3950 * setLocaleInfo method (static method)
3951 */
3952 int CVmObjDate::s_getp_setLocaleInfo(VMG_ vm_val_t *retval, uint *oargc)
3953 {
3954 /* check arguments */
3955 uint argc = (oargc != 0 ? *oargc : 0);
3956 static CVmNativeCodeDesc desc(0, 0, TRUE);
3957 if (get_prop_check_argc(retval, oargc, &desc))
3958 return TRUE;
3959
3960 /* set up a locale state interface */
3961 CVmDateLocale lc Pvmg0_P;
3962
3963 /* parse arguments */
3964 vm_val_t *argp = G_stk->get(0);
3965 if (argc == 1 && argp->is_listlike(vmg0_))
3966 {
3967 /* list of the first N elements */
3968 int n = argp->ll_length(vmg0_);
3969 for (int i = 0 ; i < n ; ++i)
3970 {
3971 /* get the element */
3972 vm_val_t ele;
3973 argp->ll_index(vmg_ &ele, i+1);
3974
3975 /* set the next index */
3976 lc.set(vmg_ G_undo, i, &ele);
3977 }
3978 }
3979 else if ((argc & 0x0001) == 0)
3980 {
3981 /* even number of arguments; treat them Type, String pairs */
3982 for (uint i = 0 ; i < argc ; i += 2, argp -= 2)
3983 lc.set(vmg_ G_undo, argp->num_to_int(vmg0_), argp - 1);
3984 }
3985 else
3986 {
3987 /* unknown arguments */
3988 err_throw(VMERR_WRONG_NUM_OF_ARGS);
3989 }
3990
3991 /* discard arguments */
3992 G_stk->discard(argc);
3993
3994 /* handled */
3995 return TRUE;
3996 }