Ruby 3.2.1p31 (2023-02-08 revision 31819e82c88c6f8ecfaeb162519bfa26a14b21fd)
time.c
1/**********************************************************************
2
3 time.c -
4
5 $Author$
6 created at: Tue Dec 28 14:31:59 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#define _DEFAULT_SOURCE
13#define _BSD_SOURCE
14#include "ruby/internal/config.h"
15
16#include <errno.h>
17#include <float.h>
18#include <math.h>
19#include <time.h>
20#include <sys/types.h>
21
22#ifdef HAVE_UNISTD_H
23# include <unistd.h>
24#endif
25
26#ifdef HAVE_STRINGS_H
27# include <strings.h>
28#endif
29
30#if defined(HAVE_SYS_TIME_H)
31# include <sys/time.h>
32#endif
33
34#include "id.h"
35#include "internal.h"
36#include "internal/array.h"
37#include "internal/hash.h"
38#include "internal/compar.h"
39#include "internal/numeric.h"
40#include "internal/rational.h"
41#include "internal/string.h"
42#include "internal/time.h"
43#include "internal/variable.h"
44#include "ruby/encoding.h"
45#include "timev.h"
46
47#include "builtin.h"
48
49static ID id_submicro, id_nano_num, id_nano_den, id_offset, id_zone;
50static ID id_nanosecond, id_microsecond, id_millisecond, id_nsec, id_usec;
51static ID id_local_to_utc, id_utc_to_local, id_find_timezone;
52static ID id_year, id_mon, id_mday, id_hour, id_min, id_sec, id_isdst;
53static VALUE str_utc, str_empty;
54
55// used by deconstruct_keys
56static VALUE sym_year, sym_month, sym_day, sym_yday, sym_wday;
57static VALUE sym_hour, sym_min, sym_sec, sym_subsec, sym_dst, sym_zone;
58
59#define id_quo idQuo
60#define id_div idDiv
61#define id_divmod idDivmod
62#define id_name idName
63#define UTC_ZONE Qundef
64
65#ifndef TM_IS_TIME
66#define TM_IS_TIME 1
67#endif
68
69#define NDIV(x,y) (-(-((x)+1)/(y))-1)
70#define NMOD(x,y) ((y)-(-((x)+1)%(y))-1)
71#define DIV(n,d) ((n)<0 ? NDIV((n),(d)) : (n)/(d))
72#define MOD(n,d) ((n)<0 ? NMOD((n),(d)) : (n)%(d))
73#define VTM_WDAY_INITVAL (7)
74#define VTM_ISDST_INITVAL (3)
75
76static int
77eq(VALUE x, VALUE y)
78{
79 if (FIXNUM_P(x) && FIXNUM_P(y)) {
80 return x == y;
81 }
82 return RTEST(rb_funcall(x, idEq, 1, y));
83}
84
85static int
86cmp(VALUE x, VALUE y)
87{
88 if (FIXNUM_P(x) && FIXNUM_P(y)) {
89 if ((long)x < (long)y)
90 return -1;
91 if ((long)x > (long)y)
92 return 1;
93 return 0;
94 }
95 if (RB_BIGNUM_TYPE_P(x)) return FIX2INT(rb_big_cmp(x, y));
96 return rb_cmpint(rb_funcall(x, idCmp, 1, y), x, y);
97}
98
99#define ne(x,y) (!eq((x),(y)))
100#define lt(x,y) (cmp((x),(y)) < 0)
101#define gt(x,y) (cmp((x),(y)) > 0)
102#define le(x,y) (cmp((x),(y)) <= 0)
103#define ge(x,y) (cmp((x),(y)) >= 0)
104
105static VALUE
106addv(VALUE x, VALUE y)
107{
108 if (FIXNUM_P(x) && FIXNUM_P(y)) {
109 return LONG2NUM(FIX2LONG(x) + FIX2LONG(y));
110 }
111 if (RB_BIGNUM_TYPE_P(x)) return rb_big_plus(x, y);
112 return rb_funcall(x, '+', 1, y);
113}
114
115static VALUE
116subv(VALUE x, VALUE y)
117{
118 if (FIXNUM_P(x) && FIXNUM_P(y)) {
119 return LONG2NUM(FIX2LONG(x) - FIX2LONG(y));
120 }
121 if (RB_BIGNUM_TYPE_P(x)) return rb_big_minus(x, y);
122 return rb_funcall(x, '-', 1, y);
123}
124
125static VALUE
126mulv(VALUE x, VALUE y)
127{
128 if (FIXNUM_P(x) && FIXNUM_P(y)) {
129 return rb_fix_mul_fix(x, y);
130 }
131 if (RB_BIGNUM_TYPE_P(x))
132 return rb_big_mul(x, y);
133 return rb_funcall(x, '*', 1, y);
134}
135
136static VALUE
137divv(VALUE x, VALUE y)
138{
139 if (FIXNUM_P(x) && FIXNUM_P(y)) {
140 return rb_fix_div_fix(x, y);
141 }
142 if (RB_BIGNUM_TYPE_P(x))
143 return rb_big_div(x, y);
144 return rb_funcall(x, id_div, 1, y);
145}
146
147static VALUE
148modv(VALUE x, VALUE y)
149{
150 if (FIXNUM_P(y)) {
151 if (FIX2LONG(y) == 0) rb_num_zerodiv();
152 if (FIXNUM_P(x)) return rb_fix_mod_fix(x, y);
153 }
154 if (RB_BIGNUM_TYPE_P(x)) return rb_big_modulo(x, y);
155 return rb_funcall(x, '%', 1, y);
156}
157
158#define neg(x) (subv(INT2FIX(0), (x)))
159
160static VALUE
161quor(VALUE x, VALUE y)
162{
163 if (FIXNUM_P(x) && FIXNUM_P(y)) {
164 long a, b, c;
165 a = FIX2LONG(x);
166 b = FIX2LONG(y);
167 if (b == 0) rb_num_zerodiv();
168 if (a == FIXNUM_MIN && b == -1) return LONG2NUM(-a);
169 c = a / b;
170 if (c * b == a) {
171 return LONG2FIX(c);
172 }
173 }
174 return rb_numeric_quo(x, y);
175}
176
177static VALUE
178quov(VALUE x, VALUE y)
179{
180 VALUE ret = quor(x, y);
181 if (RB_TYPE_P(ret, T_RATIONAL) &&
182 RRATIONAL(ret)->den == INT2FIX(1)) {
183 ret = RRATIONAL(ret)->num;
184 }
185 return ret;
186}
187
188#define mulquov(x,y,z) (((y) == (z)) ? (x) : quov(mulv((x),(y)),(z)))
189
190static void
191divmodv(VALUE n, VALUE d, VALUE *q, VALUE *r)
192{
193 VALUE tmp, ary;
194 if (FIXNUM_P(d)) {
195 if (FIX2LONG(d) == 0) rb_num_zerodiv();
196 if (FIXNUM_P(n)) {
197 rb_fix_divmod_fix(n, d, q, r);
198 return;
199 }
200 }
201 tmp = rb_funcall(n, id_divmod, 1, d);
202 ary = rb_check_array_type(tmp);
203 if (NIL_P(ary)) {
204 rb_raise(rb_eTypeError, "unexpected divmod result: into %"PRIsVALUE,
205 rb_obj_class(tmp));
206 }
207 *q = rb_ary_entry(ary, 0);
208 *r = rb_ary_entry(ary, 1);
209}
210
211#if SIZEOF_LONG == 8
212# define INT64toNUM(x) LONG2NUM(x)
213#elif defined(HAVE_LONG_LONG) && SIZEOF_LONG_LONG == 8
214# define INT64toNUM(x) LL2NUM(x)
215#endif
216
217#if defined(HAVE_UINT64_T) && SIZEOF_LONG*2 <= SIZEOF_UINT64_T
218 typedef uint64_t uwideint_t;
219 typedef int64_t wideint_t;
220 typedef uint64_t WIDEVALUE;
221 typedef int64_t SIGNED_WIDEVALUE;
222# define WIDEVALUE_IS_WIDER 1
223# define UWIDEINT_MAX UINT64_MAX
224# define WIDEINT_MAX INT64_MAX
225# define WIDEINT_MIN INT64_MIN
226# define FIXWINT_P(tv) ((tv) & 1)
227# define FIXWVtoINT64(tv) RSHIFT((SIGNED_WIDEVALUE)(tv), 1)
228# define INT64toFIXWV(wi) ((WIDEVALUE)((SIGNED_WIDEVALUE)(wi) << 1 | FIXNUM_FLAG))
229# define FIXWV_MAX (((int64_t)1 << 62) - 1)
230# define FIXWV_MIN (-((int64_t)1 << 62))
231# define FIXWVABLE(wi) (POSFIXWVABLE(wi) && NEGFIXWVABLE(wi))
232# define WINT2FIXWV(i) WIDEVAL_WRAP(INT64toFIXWV(i))
233# define FIXWV2WINT(w) FIXWVtoINT64(WIDEVAL_GET(w))
234#else
235 typedef unsigned long uwideint_t;
236 typedef long wideint_t;
237 typedef VALUE WIDEVALUE;
238 typedef SIGNED_VALUE SIGNED_WIDEVALUE;
239# define WIDEVALUE_IS_WIDER 0
240# define UWIDEINT_MAX ULONG_MAX
241# define WIDEINT_MAX LONG_MAX
242# define WIDEINT_MIN LONG_MIN
243# define FIXWINT_P(v) FIXNUM_P(v)
244# define FIXWV_MAX FIXNUM_MAX
245# define FIXWV_MIN FIXNUM_MIN
246# define FIXWVABLE(i) FIXABLE(i)
247# define WINT2FIXWV(i) WIDEVAL_WRAP(LONG2FIX(i))
248# define FIXWV2WINT(w) FIX2LONG(WIDEVAL_GET(w))
249#endif
250
251#define POSFIXWVABLE(wi) ((wi) < FIXWV_MAX+1)
252#define NEGFIXWVABLE(wi) ((wi) >= FIXWV_MIN)
253#define FIXWV_P(w) FIXWINT_P(WIDEVAL_GET(w))
254#define MUL_OVERFLOW_FIXWV_P(a, b) MUL_OVERFLOW_SIGNED_INTEGER_P(a, b, FIXWV_MIN, FIXWV_MAX)
255
256/* #define STRUCT_WIDEVAL */
257#ifdef STRUCT_WIDEVAL
258 /* for type checking */
259 typedef struct {
260 WIDEVALUE value;
261 } wideval_t;
262 static inline wideval_t WIDEVAL_WRAP(WIDEVALUE v) { wideval_t w = { v }; return w; }
263# define WIDEVAL_GET(w) ((w).value)
264#else
265 typedef WIDEVALUE wideval_t;
266# define WIDEVAL_WRAP(v) (v)
267# define WIDEVAL_GET(w) (w)
268#endif
269
270#if WIDEVALUE_IS_WIDER
271 static inline wideval_t
272 wint2wv(wideint_t wi)
273 {
274 if (FIXWVABLE(wi))
275 return WINT2FIXWV(wi);
276 else
277 return WIDEVAL_WRAP(INT64toNUM(wi));
278 }
279# define WINT2WV(wi) wint2wv(wi)
280#else
281# define WINT2WV(wi) WIDEVAL_WRAP(LONG2NUM(wi))
282#endif
283
284static inline VALUE
285w2v(wideval_t w)
286{
287#if WIDEVALUE_IS_WIDER
288 if (FIXWV_P(w))
289 return INT64toNUM(FIXWV2WINT(w));
290 return (VALUE)WIDEVAL_GET(w);
291#else
292 return WIDEVAL_GET(w);
293#endif
294}
295
296#if WIDEVALUE_IS_WIDER
297static wideval_t
298v2w_bignum(VALUE v)
299{
300 int sign;
301 uwideint_t u;
302 sign = rb_integer_pack(v, &u, 1, sizeof(u), 0,
304 if (sign == 0)
305 return WINT2FIXWV(0);
306 else if (sign == -1) {
307 if (u <= -FIXWV_MIN)
308 return WINT2FIXWV(-(wideint_t)u);
309 }
310 else if (sign == +1) {
311 if (u <= FIXWV_MAX)
312 return WINT2FIXWV((wideint_t)u);
313 }
314 return WIDEVAL_WRAP(v);
315}
316#endif
317
318static inline wideval_t
319v2w(VALUE v)
320{
321 if (RB_TYPE_P(v, T_RATIONAL)) {
322 if (RRATIONAL(v)->den != LONG2FIX(1))
323 return WIDEVAL_WRAP(v);
324 v = RRATIONAL(v)->num;
325 }
326#if WIDEVALUE_IS_WIDER
327 if (FIXNUM_P(v)) {
328 return WIDEVAL_WRAP((WIDEVALUE)(SIGNED_WIDEVALUE)(long)v);
329 }
330 else if (RB_BIGNUM_TYPE_P(v) &&
331 rb_absint_size(v, NULL) <= sizeof(WIDEVALUE)) {
332 return v2w_bignum(v);
333 }
334#endif
335 return WIDEVAL_WRAP(v);
336}
337
338static int
339weq(wideval_t wx, wideval_t wy)
340{
341#if WIDEVALUE_IS_WIDER
342 if (FIXWV_P(wx) && FIXWV_P(wy)) {
343 return WIDEVAL_GET(wx) == WIDEVAL_GET(wy);
344 }
345 return RTEST(rb_funcall(w2v(wx), idEq, 1, w2v(wy)));
346#else
347 return eq(WIDEVAL_GET(wx), WIDEVAL_GET(wy));
348#endif
349}
350
351static int
352wcmp(wideval_t wx, wideval_t wy)
353{
354 VALUE x, y;
355#if WIDEVALUE_IS_WIDER
356 if (FIXWV_P(wx) && FIXWV_P(wy)) {
357 wideint_t a, b;
358 a = FIXWV2WINT(wx);
359 b = FIXWV2WINT(wy);
360 if (a < b)
361 return -1;
362 if (a > b)
363 return 1;
364 return 0;
365 }
366#endif
367 x = w2v(wx);
368 y = w2v(wy);
369 return cmp(x, y);
370}
371
372#define wne(x,y) (!weq((x),(y)))
373#define wlt(x,y) (wcmp((x),(y)) < 0)
374#define wgt(x,y) (wcmp((x),(y)) > 0)
375#define wle(x,y) (wcmp((x),(y)) <= 0)
376#define wge(x,y) (wcmp((x),(y)) >= 0)
377
378static wideval_t
379wadd(wideval_t wx, wideval_t wy)
380{
381#if WIDEVALUE_IS_WIDER
382 if (FIXWV_P(wx) && FIXWV_P(wy)) {
383 wideint_t r = FIXWV2WINT(wx) + FIXWV2WINT(wy);
384 return WINT2WV(r);
385 }
386#endif
387 return v2w(addv(w2v(wx), w2v(wy)));
388}
389
390static wideval_t
391wsub(wideval_t wx, wideval_t wy)
392{
393#if WIDEVALUE_IS_WIDER
394 if (FIXWV_P(wx) && FIXWV_P(wy)) {
395 wideint_t r = FIXWV2WINT(wx) - FIXWV2WINT(wy);
396 return WINT2WV(r);
397 }
398#endif
399 return v2w(subv(w2v(wx), w2v(wy)));
400}
401
402static wideval_t
403wmul(wideval_t wx, wideval_t wy)
404{
405#if WIDEVALUE_IS_WIDER
406 if (FIXWV_P(wx) && FIXWV_P(wy)) {
407 if (!MUL_OVERFLOW_FIXWV_P(FIXWV2WINT(wx), FIXWV2WINT(wy)))
408 return WINT2WV(FIXWV2WINT(wx) * FIXWV2WINT(wy));
409 }
410#endif
411 return v2w(mulv(w2v(wx), w2v(wy)));
412}
413
414static wideval_t
415wquo(wideval_t wx, wideval_t wy)
416{
417#if WIDEVALUE_IS_WIDER
418 if (FIXWV_P(wx) && FIXWV_P(wy)) {
419 wideint_t a, b, c;
420 a = FIXWV2WINT(wx);
421 b = FIXWV2WINT(wy);
422 if (b == 0) rb_num_zerodiv();
423 c = a / b;
424 if (c * b == a) {
425 return WINT2WV(c);
426 }
427 }
428#endif
429 return v2w(quov(w2v(wx), w2v(wy)));
430}
431
432#define wmulquo(x,y,z) ((WIDEVAL_GET(y) == WIDEVAL_GET(z)) ? (x) : wquo(wmul((x),(y)),(z)))
433#define wmulquoll(x,y,z) (((y) == (z)) ? (x) : wquo(wmul((x),WINT2WV(y)),WINT2WV(z)))
434
435#if WIDEVALUE_IS_WIDER
436static int
437wdivmod0(wideval_t wn, wideval_t wd, wideval_t *wq, wideval_t *wr)
438{
439 if (FIXWV_P(wn) && FIXWV_P(wd)) {
440 wideint_t n, d, q, r;
441 d = FIXWV2WINT(wd);
442 if (d == 0) rb_num_zerodiv();
443 if (d == 1) {
444 *wq = wn;
445 *wr = WINT2FIXWV(0);
446 return 1;
447 }
448 if (d == -1) {
449 wideint_t xneg = -FIXWV2WINT(wn);
450 *wq = WINT2WV(xneg);
451 *wr = WINT2FIXWV(0);
452 return 1;
453 }
454 n = FIXWV2WINT(wn);
455 if (n == 0) {
456 *wq = WINT2FIXWV(0);
457 *wr = WINT2FIXWV(0);
458 return 1;
459 }
460 q = n / d;
461 r = n % d;
462 if (d > 0 ? r < 0 : r > 0) {
463 q -= 1;
464 r += d;
465 }
466 *wq = WINT2FIXWV(q);
467 *wr = WINT2FIXWV(r);
468 return 1;
469 }
470 return 0;
471}
472#endif
473
474static void
475wdivmod(wideval_t wn, wideval_t wd, wideval_t *wq, wideval_t *wr)
476{
477 VALUE vq, vr;
478#if WIDEVALUE_IS_WIDER
479 if (wdivmod0(wn, wd, wq, wr)) return;
480#endif
481 divmodv(w2v(wn), w2v(wd), &vq, &vr);
482 *wq = v2w(vq);
483 *wr = v2w(vr);
484}
485
486static void
487wmuldivmod(wideval_t wx, wideval_t wy, wideval_t wz, wideval_t *wq, wideval_t *wr)
488{
489 if (WIDEVAL_GET(wy) == WIDEVAL_GET(wz)) {
490 *wq = wx;
491 *wr = WINT2FIXWV(0);
492 return;
493 }
494 wdivmod(wmul(wx,wy), wz, wq, wr);
495}
496
497static wideval_t
498wdiv(wideval_t wx, wideval_t wy)
499{
500#if WIDEVALUE_IS_WIDER
501 wideval_t q, dmy;
502 if (wdivmod0(wx, wy, &q, &dmy)) return q;
503#endif
504 return v2w(divv(w2v(wx), w2v(wy)));
505}
506
507static wideval_t
508wmod(wideval_t wx, wideval_t wy)
509{
510#if WIDEVALUE_IS_WIDER
511 wideval_t r, dmy;
512 if (wdivmod0(wx, wy, &dmy, &r)) return r;
513#endif
514 return v2w(modv(w2v(wx), w2v(wy)));
515}
516
517static VALUE
518num_exact_check(VALUE v)
519{
520 VALUE tmp;
521
522 switch (TYPE(v)) {
523 case T_FIXNUM:
524 case T_BIGNUM:
525 tmp = v;
526 break;
527
528 case T_RATIONAL:
529 tmp = rb_rational_canonicalize(v);
530 break;
531
532 default:
533 if (!UNDEF_P(tmp = rb_check_funcall(v, idTo_r, 0, NULL))) {
534 /* test to_int method availability to reject non-Numeric
535 * objects such as String, Time, etc which have to_r method. */
536 if (!rb_respond_to(v, idTo_int)) {
537 /* FALLTHROUGH */
538 }
539 else if (RB_INTEGER_TYPE_P(tmp)) {
540 break;
541 }
542 else if (RB_TYPE_P(tmp, T_RATIONAL)) {
543 tmp = rb_rational_canonicalize(tmp);
544 break;
545 }
546 }
547 else if (!NIL_P(tmp = rb_check_to_int(v))) {
548 return tmp;
549 }
550
551 case T_NIL:
552 case T_STRING:
553 return Qnil;
554 }
555 ASSUME(!NIL_P(tmp));
556 return tmp;
557}
558
559NORETURN(static void num_exact_fail(VALUE v));
560static void
561num_exact_fail(VALUE v)
562{
563 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into an exact number",
564 rb_obj_class(v));
565}
566
567static VALUE
568num_exact(VALUE v)
569{
570 VALUE num = num_exact_check(v);
571 if (NIL_P(num)) num_exact_fail(v);
572 return num;
573}
574
575/* time_t */
576
577static wideval_t
578rb_time_magnify(wideval_t w)
579{
580 return wmul(w, WINT2FIXWV(TIME_SCALE));
581}
582
583static VALUE
584rb_time_unmagnify_to_rational(wideval_t w)
585{
586 return quor(w2v(w), INT2FIX(TIME_SCALE));
587}
588
589static wideval_t
590rb_time_unmagnify(wideval_t w)
591{
592 return v2w(rb_time_unmagnify_to_rational(w));
593}
594
595static VALUE
596rb_time_unmagnify_to_float(wideval_t w)
597{
598 VALUE v;
599#if WIDEVALUE_IS_WIDER
600 if (FIXWV_P(w)) {
601 wideint_t a, b, c;
602 a = FIXWV2WINT(w);
603 b = TIME_SCALE;
604 c = a / b;
605 if (c * b == a) {
606 return DBL2NUM((double)c);
607 }
608 v = DBL2NUM((double)FIXWV2WINT(w));
609 return quov(v, DBL2NUM(TIME_SCALE));
610 }
611#endif
612 v = w2v(w);
613 if (RB_TYPE_P(v, T_RATIONAL))
614 return rb_Float(quov(v, INT2FIX(TIME_SCALE)));
615 else
616 return quov(v, DBL2NUM(TIME_SCALE));
617}
618
619static void
620split_second(wideval_t timew, wideval_t *timew_p, VALUE *subsecx_p)
621{
622 wideval_t q, r;
623 wdivmod(timew, WINT2FIXWV(TIME_SCALE), &q, &r);
624 *timew_p = q;
625 *subsecx_p = w2v(r);
626}
627
628static wideval_t
629timet2wv(time_t t)
630{
631#if WIDEVALUE_IS_WIDER
632 if (TIMET_MIN == 0) {
633 uwideint_t wi = (uwideint_t)t;
634 if (wi <= FIXWV_MAX) {
635 return WINT2FIXWV(wi);
636 }
637 }
638 else {
639 wideint_t wi = (wideint_t)t;
640 if (FIXWV_MIN <= wi && wi <= FIXWV_MAX) {
641 return WINT2FIXWV(wi);
642 }
643 }
644#endif
645 return v2w(TIMET2NUM(t));
646}
647#define TIMET2WV(t) timet2wv(t)
648
649static time_t
650wv2timet(wideval_t w)
651{
652#if WIDEVALUE_IS_WIDER
653 if (FIXWV_P(w)) {
654 wideint_t wi = FIXWV2WINT(w);
655 if (TIMET_MIN == 0) {
656 if (wi < 0)
657 rb_raise(rb_eRangeError, "negative value to convert into `time_t'");
658 if (TIMET_MAX < (uwideint_t)wi)
659 rb_raise(rb_eRangeError, "too big to convert into `time_t'");
660 }
661 else {
662 if (wi < TIMET_MIN || TIMET_MAX < wi)
663 rb_raise(rb_eRangeError, "too big to convert into `time_t'");
664 }
665 return (time_t)wi;
666 }
667#endif
668 return NUM2TIMET(w2v(w));
669}
670#define WV2TIMET(t) wv2timet(t)
671
673static VALUE rb_cTimeTM;
674
675static int obj2int(VALUE obj);
676static uint32_t obj2ubits(VALUE obj, unsigned int bits);
677static VALUE obj2vint(VALUE obj);
678static uint32_t month_arg(VALUE arg);
679static VALUE validate_utc_offset(VALUE utc_offset);
680static VALUE validate_zone_name(VALUE zone_name);
681static void validate_vtm(struct vtm *vtm);
682static void vtm_add_day(struct vtm *vtm, int day);
683static uint32_t obj2subsecx(VALUE obj, VALUE *subsecx);
684
685static VALUE time_gmtime(VALUE);
686static VALUE time_localtime(VALUE);
687static VALUE time_fixoff(VALUE);
688static VALUE time_zonelocal(VALUE time, VALUE off);
689
690static time_t timegm_noleapsecond(struct tm *tm);
691static int tmcmp(struct tm *a, struct tm *b);
692static int vtmcmp(struct vtm *a, struct vtm *b);
693static const char *find_time_t(struct tm *tptr, int utc_p, time_t *tp);
694
695static struct vtm *localtimew(wideval_t timew, struct vtm *result);
696
697static int leap_year_p(long y);
698#define leap_year_v_p(y) leap_year_p(NUM2LONG(modv((y), INT2FIX(400))))
699
700static VALUE tm_from_time(VALUE klass, VALUE time);
701
702bool ruby_tz_uptodate_p;
703
704void
705ruby_reset_timezone(void)
706{
707 ruby_tz_uptodate_p = false;
708 ruby_reset_leap_second_info();
709}
710
711static void
712update_tz(void)
713{
714 if (ruby_tz_uptodate_p) return;
715 ruby_tz_uptodate_p = true;
716 tzset();
717}
718
719static struct tm *
720rb_localtime_r(const time_t *t, struct tm *result)
721{
722#if defined __APPLE__ && defined __LP64__
723 if (*t != (time_t)(int)*t) return NULL;
724#endif
725 update_tz();
726#ifdef HAVE_GMTIME_R
727 result = localtime_r(t, result);
728#else
729 {
730 struct tm *tmp = localtime(t);
731 if (tmp) *result = *tmp;
732 }
733#endif
734#if defined(HAVE_MKTIME) && defined(LOCALTIME_OVERFLOW_PROBLEM)
735 if (result) {
736 long gmtoff1 = 0;
737 long gmtoff2 = 0;
738 struct tm tmp = *result;
739 time_t t2;
740 t2 = mktime(&tmp);
741# if defined(HAVE_STRUCT_TM_TM_GMTOFF)
742 gmtoff1 = result->tm_gmtoff;
743 gmtoff2 = tmp.tm_gmtoff;
744# endif
745 if (*t + gmtoff1 != t2 + gmtoff2)
746 result = NULL;
747 }
748#endif
749 return result;
750}
751#define LOCALTIME(tm, result) rb_localtime_r((tm), &(result))
752
753#ifndef HAVE_STRUCT_TM_TM_GMTOFF
754static struct tm *
755rb_gmtime_r(const time_t *t, struct tm *result)
756{
757#ifdef HAVE_GMTIME_R
758 result = gmtime_r(t, result);
759#else
760 struct tm *tmp = gmtime(t);
761 if (tmp) *result = *tmp;
762#endif
763#if defined(HAVE_TIMEGM) && defined(LOCALTIME_OVERFLOW_PROBLEM)
764 if (result && *t != timegm(result)) {
765 return NULL;
766 }
767#endif
768 return result;
769}
770# define GMTIME(tm, result) rb_gmtime_r((tm), &(result))
771#endif
772
773static const int16_t common_year_yday_offset[] = {
774 -1,
775 -1 + 31,
776 -1 + 31 + 28,
777 -1 + 31 + 28 + 31,
778 -1 + 31 + 28 + 31 + 30,
779 -1 + 31 + 28 + 31 + 30 + 31,
780 -1 + 31 + 28 + 31 + 30 + 31 + 30,
781 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31,
782 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31,
783 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
784 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
785 -1 + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30
786 /* 1 2 3 4 5 6 7 8 9 10 11 */
787};
788static const int16_t leap_year_yday_offset[] = {
789 -1,
790 -1 + 31,
791 -1 + 31 + 29,
792 -1 + 31 + 29 + 31,
793 -1 + 31 + 29 + 31 + 30,
794 -1 + 31 + 29 + 31 + 30 + 31,
795 -1 + 31 + 29 + 31 + 30 + 31 + 30,
796 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31,
797 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31,
798 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30,
799 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31,
800 -1 + 31 + 29 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30
801 /* 1 2 3 4 5 6 7 8 9 10 11 */
802};
803
804static const int8_t common_year_days_in_month[] = {
805 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
806};
807static const int8_t leap_year_days_in_month[] = {
808 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
809};
810
811#define days_in_month_of(leap) ((leap) ? leap_year_days_in_month : common_year_days_in_month)
812#define days_in_month_in(y) days_in_month_of(leap_year_p(y))
813#define days_in_month_in_v(y) days_in_month_of(leap_year_v_p(y))
814
815#define M28(m) \
816 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
817 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
818 (m),(m),(m),(m),(m),(m),(m),(m)
819#define M29(m) \
820 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
821 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
822 (m),(m),(m),(m),(m),(m),(m),(m),(m)
823#define M30(m) \
824 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
825 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
826 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m)
827#define M31(m) \
828 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
829 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), \
830 (m),(m),(m),(m),(m),(m),(m),(m),(m),(m), (m)
831
832static const uint8_t common_year_mon_of_yday[] = {
833 M31(1), M28(2), M31(3), M30(4), M31(5), M30(6),
834 M31(7), M31(8), M30(9), M31(10), M30(11), M31(12)
835};
836static const uint8_t leap_year_mon_of_yday[] = {
837 M31(1), M29(2), M31(3), M30(4), M31(5), M30(6),
838 M31(7), M31(8), M30(9), M31(10), M30(11), M31(12)
839};
840
841#undef M28
842#undef M29
843#undef M30
844#undef M31
845
846#define D28 \
847 1,2,3,4,5,6,7,8,9, \
848 10,11,12,13,14,15,16,17,18,19, \
849 20,21,22,23,24,25,26,27,28
850#define D29 \
851 1,2,3,4,5,6,7,8,9, \
852 10,11,12,13,14,15,16,17,18,19, \
853 20,21,22,23,24,25,26,27,28,29
854#define D30 \
855 1,2,3,4,5,6,7,8,9, \
856 10,11,12,13,14,15,16,17,18,19, \
857 20,21,22,23,24,25,26,27,28,29,30
858#define D31 \
859 1,2,3,4,5,6,7,8,9, \
860 10,11,12,13,14,15,16,17,18,19, \
861 20,21,22,23,24,25,26,27,28,29,30,31
862
863static const uint8_t common_year_mday_of_yday[] = {
864 /* 1 2 3 4 5 6 7 8 9 10 11 12 */
865 D31, D28, D31, D30, D31, D30, D31, D31, D30, D31, D30, D31
866};
867static const uint8_t leap_year_mday_of_yday[] = {
868 D31, D29, D31, D30, D31, D30, D31, D31, D30, D31, D30, D31
869};
870
871#undef D28
872#undef D29
873#undef D30
874#undef D31
875
876static int
877calc_tm_yday(long tm_year, int tm_mon, int tm_mday)
878{
879 int tm_year_mod400 = (int)MOD(tm_year, 400);
880 int tm_yday = tm_mday;
881
882 if (leap_year_p(tm_year_mod400 + 1900))
883 tm_yday += leap_year_yday_offset[tm_mon];
884 else
885 tm_yday += common_year_yday_offset[tm_mon];
886
887 return tm_yday;
888}
889
890static wideval_t
891timegmw_noleapsecond(struct vtm *vtm)
892{
893 VALUE year1900;
894 VALUE q400, r400;
895 int year_mod400;
896 int yday;
897 long days_in400;
898 VALUE vdays, ret;
899 wideval_t wret;
900
901 year1900 = subv(vtm->year, INT2FIX(1900));
902
903 divmodv(year1900, INT2FIX(400), &q400, &r400);
904 year_mod400 = NUM2INT(r400);
905
906 yday = calc_tm_yday(year_mod400, vtm->mon-1, vtm->mday);
907
908 /*
909 * `Seconds Since the Epoch' in SUSv3:
910 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
911 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
912 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
913 */
914 ret = LONG2NUM(vtm->sec
915 + vtm->min*60
916 + vtm->hour*3600);
917 days_in400 = yday
918 - 70*365
919 + DIV(year_mod400 - 69, 4)
920 - DIV(year_mod400 - 1, 100)
921 + (year_mod400 + 299) / 400;
922 vdays = LONG2NUM(days_in400);
923 vdays = addv(vdays, mulv(q400, INT2FIX(97)));
924 vdays = addv(vdays, mulv(year1900, INT2FIX(365)));
925 wret = wadd(rb_time_magnify(v2w(ret)), wmul(rb_time_magnify(v2w(vdays)), WINT2FIXWV(86400)));
926 wret = wadd(wret, v2w(vtm->subsecx));
927
928 return wret;
929}
930
931static VALUE
932zone_str(const char *zone)
933{
934 const char *p;
935 int ascii_only = 1;
936 VALUE str;
937 size_t len;
938
939 if (zone == NULL) {
940 return rb_fstring_lit("(NO-TIMEZONE-ABBREVIATION)");
941 }
942
943 for (p = zone; *p; p++)
944 if (!ISASCII(*p)) {
945 ascii_only = 0;
946 break;
947 }
948 len = p - zone + strlen(p);
949 if (ascii_only) {
950 str = rb_usascii_str_new(zone, len);
951 }
952 else {
953 str = rb_enc_str_new(zone, len, rb_locale_encoding());
954 }
955 return rb_fstring(str);
956}
957
958static void
959gmtimew_noleapsecond(wideval_t timew, struct vtm *vtm)
960{
961 VALUE v;
962 int n, x, y;
963 int wday;
964 VALUE timev;
965 wideval_t timew2, w, w2;
966 VALUE subsecx;
967
968 vtm->isdst = 0;
969
970 split_second(timew, &timew2, &subsecx);
971 vtm->subsecx = subsecx;
972
973 wdivmod(timew2, WINT2FIXWV(86400), &w2, &w);
974 timev = w2v(w2);
975 v = w2v(w);
976
977 wday = NUM2INT(modv(timev, INT2FIX(7)));
978 vtm->wday = (wday + 4) % 7;
979
980 n = NUM2INT(v);
981 vtm->sec = n % 60; n = n / 60;
982 vtm->min = n % 60; n = n / 60;
983 vtm->hour = n;
984
985 /* 97 leap days in the 400 year cycle */
986 divmodv(timev, INT2FIX(400*365 + 97), &timev, &v);
987 vtm->year = mulv(timev, INT2FIX(400));
988
989 /* n is the days in the 400 year cycle.
990 * the start of the cycle is 1970-01-01. */
991
992 n = NUM2INT(v);
993 y = 1970;
994
995 /* 30 years including 7 leap days (1972, 1976, ... 1996),
996 * 31 days in January 2000 and
997 * 29 days in February 2000
998 * from 1970-01-01 to 2000-02-29 */
999 if (30*365+7+31+29-1 <= n) {
1000 /* 2000-02-29 or after */
1001 if (n < 31*365+8) {
1002 /* 2000-02-29 to 2000-12-31 */
1003 y += 30;
1004 n -= 30*365+7;
1005 goto found;
1006 }
1007 else {
1008 /* 2001-01-01 or after */
1009 n -= 1;
1010 }
1011 }
1012
1013 x = n / (365*100 + 24);
1014 n = n % (365*100 + 24);
1015 y += x * 100;
1016 if (30*365+7+31+29-1 <= n) {
1017 if (n < 31*365+7) {
1018 y += 30;
1019 n -= 30*365+7;
1020 goto found;
1021 }
1022 else
1023 n += 1;
1024 }
1025
1026 x = n / (365*4 + 1);
1027 n = n % (365*4 + 1);
1028 y += x * 4;
1029 if (365*2+31+29-1 <= n) {
1030 if (n < 365*2+366) {
1031 y += 2;
1032 n -= 365*2;
1033 goto found;
1034 }
1035 else
1036 n -= 1;
1037 }
1038
1039 x = n / 365;
1040 n = n % 365;
1041 y += x;
1042
1043 found:
1044 vtm->yday = n+1;
1045 vtm->year = addv(vtm->year, INT2NUM(y));
1046
1047 if (leap_year_p(y)) {
1048 vtm->mon = leap_year_mon_of_yday[n];
1049 vtm->mday = leap_year_mday_of_yday[n];
1050 }
1051 else {
1052 vtm->mon = common_year_mon_of_yday[n];
1053 vtm->mday = common_year_mday_of_yday[n];
1054 }
1055
1056 vtm->utc_offset = INT2FIX(0);
1057 vtm->zone = str_utc;
1058}
1059
1060static struct tm *
1061gmtime_with_leapsecond(const time_t *timep, struct tm *result)
1062{
1063#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
1064 /* 4.4BSD counts leap seconds only with localtime, not with gmtime. */
1065 struct tm *t;
1066 int sign;
1067 int gmtoff_sec, gmtoff_min, gmtoff_hour, gmtoff_day;
1068 long gmtoff;
1069 t = LOCALTIME(timep, *result);
1070 if (t == NULL)
1071 return NULL;
1072
1073 /* subtract gmtoff */
1074 if (t->tm_gmtoff < 0) {
1075 sign = 1;
1076 gmtoff = -t->tm_gmtoff;
1077 }
1078 else {
1079 sign = -1;
1080 gmtoff = t->tm_gmtoff;
1081 }
1082 gmtoff_sec = (int)(gmtoff % 60);
1083 gmtoff = gmtoff / 60;
1084 gmtoff_min = (int)(gmtoff % 60);
1085 gmtoff = gmtoff / 60;
1086 gmtoff_hour = (int)gmtoff; /* <= 12 */
1087
1088 gmtoff_sec *= sign;
1089 gmtoff_min *= sign;
1090 gmtoff_hour *= sign;
1091
1092 gmtoff_day = 0;
1093
1094 if (gmtoff_sec) {
1095 /* If gmtoff_sec == 0, don't change result->tm_sec.
1096 * It may be 60 which is a leap second. */
1097 result->tm_sec += gmtoff_sec;
1098 if (result->tm_sec < 0) {
1099 result->tm_sec += 60;
1100 gmtoff_min -= 1;
1101 }
1102 if (60 <= result->tm_sec) {
1103 result->tm_sec -= 60;
1104 gmtoff_min += 1;
1105 }
1106 }
1107 if (gmtoff_min) {
1108 result->tm_min += gmtoff_min;
1109 if (result->tm_min < 0) {
1110 result->tm_min += 60;
1111 gmtoff_hour -= 1;
1112 }
1113 if (60 <= result->tm_min) {
1114 result->tm_min -= 60;
1115 gmtoff_hour += 1;
1116 }
1117 }
1118 if (gmtoff_hour) {
1119 result->tm_hour += gmtoff_hour;
1120 if (result->tm_hour < 0) {
1121 result->tm_hour += 24;
1122 gmtoff_day = -1;
1123 }
1124 if (24 <= result->tm_hour) {
1125 result->tm_hour -= 24;
1126 gmtoff_day = 1;
1127 }
1128 }
1129
1130 if (gmtoff_day) {
1131 if (gmtoff_day < 0) {
1132 if (result->tm_yday == 0) {
1133 result->tm_mday = 31;
1134 result->tm_mon = 11; /* December */
1135 result->tm_year--;
1136 result->tm_yday = leap_year_p(result->tm_year + 1900) ? 365 : 364;
1137 }
1138 else if (result->tm_mday == 1) {
1139 const int8_t *days_in_month = days_in_month_in(result->tm_year + 1900);
1140 result->tm_mon--;
1141 result->tm_mday = days_in_month[result->tm_mon];
1142 result->tm_yday--;
1143 }
1144 else {
1145 result->tm_mday--;
1146 result->tm_yday--;
1147 }
1148 result->tm_wday = (result->tm_wday + 6) % 7;
1149 }
1150 else {
1151 int leap = leap_year_p(result->tm_year + 1900);
1152 if (result->tm_yday == (leap ? 365 : 364)) {
1153 result->tm_year++;
1154 result->tm_mon = 0; /* January */
1155 result->tm_mday = 1;
1156 result->tm_yday = 0;
1157 }
1158 else if (result->tm_mday == days_in_month_of(leap)[result->tm_mon]) {
1159 result->tm_mon++;
1160 result->tm_mday = 1;
1161 result->tm_yday++;
1162 }
1163 else {
1164 result->tm_mday++;
1165 result->tm_yday++;
1166 }
1167 result->tm_wday = (result->tm_wday + 1) % 7;
1168 }
1169 }
1170 result->tm_isdst = 0;
1171 result->tm_gmtoff = 0;
1172#if defined(HAVE_TM_ZONE)
1173 result->tm_zone = (char *)"UTC";
1174#endif
1175 return result;
1176#else
1177 return GMTIME(timep, *result);
1178#endif
1179}
1180
1181static long this_year = 0;
1182static time_t known_leap_seconds_limit;
1183static int number_of_leap_seconds_known;
1184
1185static void
1186init_leap_second_info(void)
1187{
1188 /*
1189 * leap seconds are determined by IERS.
1190 * It is announced 6 months before the leap second.
1191 * So no one knows leap seconds in the future after the next year.
1192 */
1193 if (this_year == 0) {
1194 time_t now;
1195 struct tm *tm, result;
1196 struct vtm vtm;
1197 wideval_t timew;
1198 now = time(NULL);
1199#ifdef HAVE_GMTIME_R
1200 gmtime_r(&now, &result);
1201#else
1202 gmtime(&now);
1203#endif
1204 tm = gmtime_with_leapsecond(&now, &result);
1205 if (!tm) return;
1206 this_year = tm->tm_year;
1207
1208 if (TIMET_MAX - now < (time_t)(366*86400))
1209 known_leap_seconds_limit = TIMET_MAX;
1210 else
1211 known_leap_seconds_limit = now + (time_t)(366*86400);
1212
1213 if (!gmtime_with_leapsecond(&known_leap_seconds_limit, &result))
1214 return;
1215
1216 vtm.year = LONG2NUM(result.tm_year + 1900);
1217 vtm.mon = result.tm_mon + 1;
1218 vtm.mday = result.tm_mday;
1219 vtm.hour = result.tm_hour;
1220 vtm.min = result.tm_min;
1221 vtm.sec = result.tm_sec;
1222 vtm.subsecx = INT2FIX(0);
1223 vtm.utc_offset = INT2FIX(0);
1224
1225 timew = timegmw_noleapsecond(&vtm);
1226
1227 number_of_leap_seconds_known = NUM2INT(w2v(wsub(TIMET2WV(known_leap_seconds_limit), rb_time_unmagnify(timew))));
1228 }
1229}
1230
1231/* Use this if you want to re-run init_leap_second_info() */
1232void
1233ruby_reset_leap_second_info(void)
1234{
1235 this_year = 0;
1236}
1237
1238static wideval_t
1239timegmw(struct vtm *vtm)
1240{
1241 wideval_t timew;
1242 struct tm tm;
1243 time_t t;
1244 const char *errmsg;
1245
1246 /* The first leap second is 1972-06-30 23:59:60 UTC.
1247 * No leap seconds before. */
1248 if (gt(INT2FIX(1972), vtm->year))
1249 return timegmw_noleapsecond(vtm);
1250
1251 init_leap_second_info();
1252
1253 timew = timegmw_noleapsecond(vtm);
1254
1255
1256 if (number_of_leap_seconds_known == 0) {
1257 /* When init_leap_second_info() is executed, the timezone doesn't have
1258 * leap second information. Disable leap second for calculating gmtime.
1259 */
1260 return timew;
1261 }
1262 else if (wlt(rb_time_magnify(TIMET2WV(known_leap_seconds_limit)), timew)) {
1263 return wadd(timew, rb_time_magnify(WINT2WV(number_of_leap_seconds_known)));
1264 }
1265
1266 tm.tm_year = rb_long2int(NUM2LONG(vtm->year) - 1900);
1267 tm.tm_mon = vtm->mon - 1;
1268 tm.tm_mday = vtm->mday;
1269 tm.tm_hour = vtm->hour;
1270 tm.tm_min = vtm->min;
1271 tm.tm_sec = vtm->sec;
1272 tm.tm_isdst = 0;
1273
1274 errmsg = find_time_t(&tm, 1, &t);
1275 if (errmsg)
1276 rb_raise(rb_eArgError, "%s", errmsg);
1277 return wadd(rb_time_magnify(TIMET2WV(t)), v2w(vtm->subsecx));
1278}
1279
1280static struct vtm *
1281gmtimew(wideval_t timew, struct vtm *result)
1282{
1283 time_t t;
1284 struct tm tm;
1285 VALUE subsecx;
1286 wideval_t timew2;
1287
1288 if (wlt(timew, WINT2FIXWV(0))) {
1289 gmtimew_noleapsecond(timew, result);
1290 return result;
1291 }
1292
1293 init_leap_second_info();
1294
1295 if (number_of_leap_seconds_known == 0) {
1296 /* When init_leap_second_info() is executed, the timezone doesn't have
1297 * leap second information. Disable leap second for calculating gmtime.
1298 */
1299 gmtimew_noleapsecond(timew, result);
1300 return result;
1301 }
1302 else if (wlt(rb_time_magnify(TIMET2WV(known_leap_seconds_limit)), timew)) {
1303 timew = wsub(timew, rb_time_magnify(WINT2WV(number_of_leap_seconds_known)));
1304 gmtimew_noleapsecond(timew, result);
1305 return result;
1306 }
1307
1308 split_second(timew, &timew2, &subsecx);
1309
1310 t = WV2TIMET(timew2);
1311 if (!gmtime_with_leapsecond(&t, &tm))
1312 return NULL;
1313
1314 result->year = LONG2NUM((long)tm.tm_year + 1900);
1315 result->mon = tm.tm_mon + 1;
1316 result->mday = tm.tm_mday;
1317 result->hour = tm.tm_hour;
1318 result->min = tm.tm_min;
1319 result->sec = tm.tm_sec;
1320 result->subsecx = subsecx;
1321 result->utc_offset = INT2FIX(0);
1322 result->wday = tm.tm_wday;
1323 result->yday = tm.tm_yday+1;
1324 result->isdst = tm.tm_isdst;
1325#if 0
1326 result->zone = rb_fstring_lit("UTC");
1327#endif
1328
1329 return result;
1330}
1331
1332#define GMTIMEW(w, v) \
1333 (gmtimew(w, v) ? (void)0 : rb_raise(rb_eArgError, "gmtime error"))
1334
1335static struct tm *localtime_with_gmtoff_zone(const time_t *t, struct tm *result, long *gmtoff, VALUE *zone);
1336
1337/*
1338 * The idea, extrapolate localtime() function, is borrowed from Perl:
1339 * http://web.archive.org/web/20080211114141/http://use.perl.org/articles/08/02/07/197204.shtml
1340 *
1341 * compat_common_month_table is generated by the following program.
1342 * This table finds the last month which starts at the same day of a week.
1343 * The year 2037 is not used because:
1344 * https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=522949
1345 *
1346 * #!/usr/bin/ruby
1347 *
1348 * require 'date'
1349 *
1350 * h = {}
1351 * 2036.downto(2010) {|y|
1352 * 1.upto(12) {|m|
1353 * next if m == 2 && y % 4 == 0
1354 * d = Date.new(y,m,1)
1355 * h[m] ||= {}
1356 * h[m][d.wday] ||= y
1357 * }
1358 * }
1359 *
1360 * 1.upto(12) {|m|
1361 * print "{"
1362 * 0.upto(6) {|w|
1363 * y = h[m][w]
1364 * print " #{y},"
1365 * }
1366 * puts "},"
1367 * }
1368 *
1369 */
1370static const int compat_common_month_table[12][7] = {
1371 /* Sun Mon Tue Wed Thu Fri Sat */
1372 { 2034, 2035, 2036, 2031, 2032, 2027, 2033 }, /* January */
1373 { 2026, 2027, 2033, 2034, 2035, 2030, 2031 }, /* February */
1374 { 2026, 2032, 2033, 2034, 2035, 2030, 2036 }, /* March */
1375 { 2035, 2030, 2036, 2026, 2032, 2033, 2034 }, /* April */
1376 { 2033, 2034, 2035, 2030, 2036, 2026, 2032 }, /* May */
1377 { 2036, 2026, 2032, 2033, 2034, 2035, 2030 }, /* June */
1378 { 2035, 2030, 2036, 2026, 2032, 2033, 2034 }, /* July */
1379 { 2032, 2033, 2034, 2035, 2030, 2036, 2026 }, /* August */
1380 { 2030, 2036, 2026, 2032, 2033, 2034, 2035 }, /* September */
1381 { 2034, 2035, 2030, 2036, 2026, 2032, 2033 }, /* October */
1382 { 2026, 2032, 2033, 2034, 2035, 2030, 2036 }, /* November */
1383 { 2030, 2036, 2026, 2032, 2033, 2034, 2035 }, /* December */
1384};
1385
1386/*
1387 * compat_leap_month_table is generated by following program.
1388 *
1389 * #!/usr/bin/ruby
1390 *
1391 * require 'date'
1392 *
1393 * h = {}
1394 * 2037.downto(2010) {|y|
1395 * 1.upto(12) {|m|
1396 * next unless m == 2 && y % 4 == 0
1397 * d = Date.new(y,m,1)
1398 * h[m] ||= {}
1399 * h[m][d.wday] ||= y
1400 * }
1401 * }
1402 *
1403 * 2.upto(2) {|m|
1404 * 0.upto(6) {|w|
1405 * y = h[m][w]
1406 * print " #{y},"
1407 * }
1408 * puts
1409 * }
1410 */
1411static const int compat_leap_month_table[7] = {
1412/* Sun Mon Tue Wed Thu Fri Sat */
1413 2032, 2016, 2028, 2012, 2024, 2036, 2020, /* February */
1414};
1415
1416static int
1417calc_wday(int year_mod400, int month, int day)
1418{
1419 int a, y, m;
1420 int wday;
1421
1422 a = (14 - month) / 12;
1423 y = year_mod400 + 4800 - a;
1424 m = month + 12 * a - 3;
1425 wday = day + (153*m+2)/5 + 365*y + y/4 - y/100 + y/400 + 2;
1426 wday = wday % 7;
1427 return wday;
1428}
1429
1430static VALUE
1431guess_local_offset(struct vtm *vtm_utc, int *isdst_ret, VALUE *zone_ret)
1432{
1433 struct tm tm;
1434 long gmtoff;
1435 VALUE zone;
1436 time_t t;
1437 struct vtm vtm2;
1438 VALUE timev;
1439 int year_mod400, wday;
1440
1441 /* Daylight Saving Time was introduced in 1916.
1442 * So we don't need to care about DST before that. */
1443 if (lt(vtm_utc->year, INT2FIX(1916))) {
1444 VALUE off = INT2FIX(0);
1445 int isdst = 0;
1446 zone = rb_fstring_lit("UTC");
1447
1448# if defined(NEGATIVE_TIME_T)
1449# if SIZEOF_TIME_T <= 4
1450 /* 1901-12-13 20:45:52 UTC : The oldest time in 32-bit signed time_t. */
1451# define THE_TIME_OLD_ENOUGH ((time_t)0x80000000)
1452# else
1453 /* Since the Royal Greenwich Observatory was commissioned in 1675,
1454 no timezone defined using GMT at 1600. */
1455# define THE_TIME_OLD_ENOUGH ((time_t)(1600-1970)*366*24*60*60)
1456# endif
1457 if (localtime_with_gmtoff_zone((t = THE_TIME_OLD_ENOUGH, &t), &tm, &gmtoff, &zone)) {
1458 off = LONG2FIX(gmtoff);
1459 isdst = tm.tm_isdst;
1460 }
1461 else
1462# endif
1463 /* 1970-01-01 00:00:00 UTC : The Unix epoch - the oldest time in portable time_t. */
1464 if (localtime_with_gmtoff_zone((t = 0, &t), &tm, &gmtoff, &zone)) {
1465 off = LONG2FIX(gmtoff);
1466 isdst = tm.tm_isdst;
1467 }
1468
1469 if (isdst_ret)
1470 *isdst_ret = isdst;
1471 if (zone_ret)
1472 *zone_ret = zone;
1473 return off;
1474 }
1475
1476 /* It is difficult to guess the future. */
1477
1478 vtm2 = *vtm_utc;
1479
1480 /* guess using a year before 2038. */
1481 year_mod400 = NUM2INT(modv(vtm_utc->year, INT2FIX(400)));
1482 wday = calc_wday(year_mod400, vtm_utc->mon, 1);
1483 if (vtm_utc->mon == 2 && leap_year_p(year_mod400))
1484 vtm2.year = INT2FIX(compat_leap_month_table[wday]);
1485 else
1486 vtm2.year = INT2FIX(compat_common_month_table[vtm_utc->mon-1][wday]);
1487
1488 timev = w2v(rb_time_unmagnify(timegmw(&vtm2)));
1489 t = NUM2TIMET(timev);
1490 zone = str_utc;
1491 if (localtime_with_gmtoff_zone(&t, &tm, &gmtoff, &zone)) {
1492 if (isdst_ret)
1493 *isdst_ret = tm.tm_isdst;
1494 if (zone_ret)
1495 *zone_ret = zone;
1496 return LONG2FIX(gmtoff);
1497 }
1498
1499 {
1500 /* Use the current time offset as a last resort. */
1501 static time_t now = 0;
1502 static long now_gmtoff = 0;
1503 static int now_isdst = 0;
1504 static VALUE now_zone;
1505 if (now == 0) {
1506 VALUE zone;
1507 now = time(NULL);
1508 localtime_with_gmtoff_zone(&now, &tm, &now_gmtoff, &zone);
1509 now_isdst = tm.tm_isdst;
1510 zone = rb_fstring(zone);
1511 rb_gc_register_mark_object(zone);
1512 now_zone = zone;
1513 }
1514 if (isdst_ret)
1515 *isdst_ret = now_isdst;
1516 if (zone_ret)
1517 *zone_ret = now_zone;
1518 return LONG2FIX(now_gmtoff);
1519 }
1520}
1521
1522static VALUE
1523small_vtm_sub(struct vtm *vtm1, struct vtm *vtm2)
1524{
1525 int off;
1526
1527 off = vtm1->sec - vtm2->sec;
1528 off += (vtm1->min - vtm2->min) * 60;
1529 off += (vtm1->hour - vtm2->hour) * 3600;
1530 if (ne(vtm1->year, vtm2->year))
1531 off += lt(vtm1->year, vtm2->year) ? -24*3600 : 24*3600;
1532 else if (vtm1->mon != vtm2->mon)
1533 off += vtm1->mon < vtm2->mon ? -24*3600 : 24*3600;
1534 else if (vtm1->mday != vtm2->mday)
1535 off += vtm1->mday < vtm2->mday ? -24*3600 : 24*3600;
1536
1537 return INT2FIX(off);
1538}
1539
1540static wideval_t
1541timelocalw(struct vtm *vtm)
1542{
1543 time_t t;
1544 struct tm tm;
1545 VALUE v;
1546 wideval_t timew1, timew2;
1547 struct vtm vtm1, vtm2;
1548 int n;
1549
1550 if (FIXNUM_P(vtm->year)) {
1551 long l = FIX2LONG(vtm->year) - 1900;
1552 if (l < INT_MIN || INT_MAX < l)
1553 goto no_localtime;
1554 tm.tm_year = (int)l;
1555 }
1556 else {
1557 v = subv(vtm->year, INT2FIX(1900));
1558 if (lt(v, INT2NUM(INT_MIN)) || lt(INT2NUM(INT_MAX), v))
1559 goto no_localtime;
1560 tm.tm_year = NUM2INT(v);
1561 }
1562
1563 tm.tm_mon = vtm->mon-1;
1564 tm.tm_mday = vtm->mday;
1565 tm.tm_hour = vtm->hour;
1566 tm.tm_min = vtm->min;
1567 tm.tm_sec = vtm->sec;
1568 tm.tm_isdst = vtm->isdst == VTM_ISDST_INITVAL ? -1 : vtm->isdst;
1569
1570 if (find_time_t(&tm, 0, &t))
1571 goto no_localtime;
1572 return wadd(rb_time_magnify(TIMET2WV(t)), v2w(vtm->subsecx));
1573
1574 no_localtime:
1575 timew1 = timegmw(vtm);
1576
1577 if (!localtimew(timew1, &vtm1))
1578 rb_raise(rb_eArgError, "localtimew error");
1579
1580 n = vtmcmp(vtm, &vtm1);
1581 if (n == 0) {
1582 timew1 = wsub(timew1, rb_time_magnify(WINT2FIXWV(12*3600)));
1583 if (!localtimew(timew1, &vtm1))
1584 rb_raise(rb_eArgError, "localtimew error");
1585 n = 1;
1586 }
1587
1588 if (n < 0) {
1589 timew2 = timew1;
1590 vtm2 = vtm1;
1591 timew1 = wsub(timew1, rb_time_magnify(WINT2FIXWV(24*3600)));
1592 if (!localtimew(timew1, &vtm1))
1593 rb_raise(rb_eArgError, "localtimew error");
1594 }
1595 else {
1596 timew2 = wadd(timew1, rb_time_magnify(WINT2FIXWV(24*3600)));
1597 if (!localtimew(timew2, &vtm2))
1598 rb_raise(rb_eArgError, "localtimew error");
1599 }
1600 timew1 = wadd(timew1, rb_time_magnify(v2w(small_vtm_sub(vtm, &vtm1))));
1601 timew2 = wadd(timew2, rb_time_magnify(v2w(small_vtm_sub(vtm, &vtm2))));
1602
1603 if (weq(timew1, timew2))
1604 return timew1;
1605
1606 if (!localtimew(timew1, &vtm1))
1607 rb_raise(rb_eArgError, "localtimew error");
1608 if (vtm->hour != vtm1.hour || vtm->min != vtm1.min || vtm->sec != vtm1.sec)
1609 return timew2;
1610
1611 if (!localtimew(timew2, &vtm2))
1612 rb_raise(rb_eArgError, "localtimew error");
1613 if (vtm->hour != vtm2.hour || vtm->min != vtm2.min || vtm->sec != vtm2.sec)
1614 return timew1;
1615
1616 if (vtm->isdst)
1617 return lt(vtm1.utc_offset, vtm2.utc_offset) ? timew2 : timew1;
1618 else
1619 return lt(vtm1.utc_offset, vtm2.utc_offset) ? timew1 : timew2;
1620}
1621
1622static struct tm *
1623localtime_with_gmtoff_zone(const time_t *t, struct tm *result, long *gmtoff, VALUE *zone)
1624{
1625 struct tm tm;
1626
1627 if (LOCALTIME(t, tm)) {
1628#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
1629 *gmtoff = tm.tm_gmtoff;
1630#else
1631 struct tm *u, *l;
1632 long off;
1633 struct tm tmbuf;
1634 l = &tm;
1635 u = GMTIME(t, tmbuf);
1636 if (!u)
1637 return NULL;
1638 if (l->tm_year != u->tm_year)
1639 off = l->tm_year < u->tm_year ? -1 : 1;
1640 else if (l->tm_mon != u->tm_mon)
1641 off = l->tm_mon < u->tm_mon ? -1 : 1;
1642 else if (l->tm_mday != u->tm_mday)
1643 off = l->tm_mday < u->tm_mday ? -1 : 1;
1644 else
1645 off = 0;
1646 off = off * 24 + l->tm_hour - u->tm_hour;
1647 off = off * 60 + l->tm_min - u->tm_min;
1648 off = off * 60 + l->tm_sec - u->tm_sec;
1649 *gmtoff = off;
1650#endif
1651
1652 if (zone) {
1653#if defined(HAVE_TM_ZONE)
1654 *zone = zone_str(tm.tm_zone);
1655#elif defined(HAVE_TZNAME) && defined(HAVE_DAYLIGHT)
1656# if defined(RUBY_MSVCRT_VERSION) && RUBY_MSVCRT_VERSION >= 140
1657# define tzname _tzname
1658# define daylight _daylight
1659# endif
1660 /* this needs tzset or localtime, instead of localtime_r */
1661 *zone = zone_str(tzname[daylight && tm.tm_isdst]);
1662#else
1663 {
1664 char buf[64];
1665 strftime(buf, sizeof(buf), "%Z", &tm);
1666 *zone = zone_str(buf);
1667 }
1668#endif
1669 }
1670
1671 *result = tm;
1672 return result;
1673 }
1674 return NULL;
1675}
1676
1677static int
1678timew_out_of_timet_range(wideval_t timew)
1679{
1680 VALUE timexv;
1681#if WIDEVALUE_IS_WIDER && SIZEOF_TIME_T < SIZEOF_INT64_T
1682 if (FIXWV_P(timew)) {
1683 wideint_t t = FIXWV2WINT(timew);
1684 if (t < TIME_SCALE * (wideint_t)TIMET_MIN ||
1685 TIME_SCALE * (1 + (wideint_t)TIMET_MAX) <= t)
1686 return 1;
1687 return 0;
1688 }
1689#endif
1690#if SIZEOF_TIME_T == SIZEOF_INT64_T
1691 if (FIXWV_P(timew)) {
1692 wideint_t t = FIXWV2WINT(timew);
1693 if (~(time_t)0 <= 0) {
1694 return 0;
1695 }
1696 else {
1697 if (t < 0)
1698 return 1;
1699 return 0;
1700 }
1701 }
1702#endif
1703 timexv = w2v(timew);
1704 if (lt(timexv, mulv(INT2FIX(TIME_SCALE), TIMET2NUM(TIMET_MIN))) ||
1705 le(mulv(INT2FIX(TIME_SCALE), addv(TIMET2NUM(TIMET_MAX), INT2FIX(1))), timexv))
1706 return 1;
1707 return 0;
1708}
1709
1710static struct vtm *
1711localtimew(wideval_t timew, struct vtm *result)
1712{
1713 VALUE subsecx, offset;
1714 VALUE zone;
1715 int isdst;
1716
1717 if (!timew_out_of_timet_range(timew)) {
1718 time_t t;
1719 struct tm tm;
1720 long gmtoff;
1721 wideval_t timew2;
1722
1723 split_second(timew, &timew2, &subsecx);
1724
1725 t = WV2TIMET(timew2);
1726
1727 if (localtime_with_gmtoff_zone(&t, &tm, &gmtoff, &zone)) {
1728 result->year = LONG2NUM((long)tm.tm_year + 1900);
1729 result->mon = tm.tm_mon + 1;
1730 result->mday = tm.tm_mday;
1731 result->hour = tm.tm_hour;
1732 result->min = tm.tm_min;
1733 result->sec = tm.tm_sec;
1734 result->subsecx = subsecx;
1735 result->wday = tm.tm_wday;
1736 result->yday = tm.tm_yday+1;
1737 result->isdst = tm.tm_isdst;
1738 result->utc_offset = LONG2NUM(gmtoff);
1739 result->zone = zone;
1740 return result;
1741 }
1742 }
1743
1744 if (!gmtimew(timew, result))
1745 return NULL;
1746
1747 offset = guess_local_offset(result, &isdst, &zone);
1748
1749 if (!gmtimew(wadd(timew, rb_time_magnify(v2w(offset))), result))
1750 return NULL;
1751
1752 result->utc_offset = offset;
1753 result->isdst = isdst;
1754 result->zone = zone;
1755
1756 return result;
1757}
1758
1759#define TIME_TZMODE_LOCALTIME 0
1760#define TIME_TZMODE_UTC 1
1761#define TIME_TZMODE_FIXOFF 2
1762#define TIME_TZMODE_UNINITIALIZED 3
1763
1764PACKED_STRUCT_UNALIGNED(struct time_object {
1765 wideval_t timew; /* time_t value * TIME_SCALE. possibly Rational. */
1766 struct vtm vtm;
1767 unsigned int tzmode:3; /* 0:localtime 1:utc 2:fixoff 3:uninitialized */
1768 unsigned int tm_got:1;
1770
1771#define GetTimeval(obj, tobj) ((tobj) = get_timeval(obj))
1772#define GetNewTimeval(obj, tobj) ((tobj) = get_new_timeval(obj))
1773
1774#define IsTimeval(obj) rb_typeddata_is_kind_of((obj), &time_data_type)
1775#define TIME_INIT_P(tobj) ((tobj)->tzmode != TIME_TZMODE_UNINITIALIZED)
1776
1777#define TZMODE_UTC_P(tobj) ((tobj)->tzmode == TIME_TZMODE_UTC)
1778#define TZMODE_SET_UTC(tobj) ((tobj)->tzmode = TIME_TZMODE_UTC)
1779
1780#define TZMODE_LOCALTIME_P(tobj) ((tobj)->tzmode == TIME_TZMODE_LOCALTIME)
1781#define TZMODE_SET_LOCALTIME(tobj) ((tobj)->tzmode = TIME_TZMODE_LOCALTIME)
1782
1783#define TZMODE_FIXOFF_P(tobj) ((tobj)->tzmode == TIME_TZMODE_FIXOFF)
1784#define TZMODE_SET_FIXOFF(tobj, off) \
1785 ((tobj)->tzmode = TIME_TZMODE_FIXOFF, \
1786 (tobj)->vtm.utc_offset = (off))
1787
1788#define TZMODE_COPY(tobj1, tobj2) \
1789 ((tobj1)->tzmode = (tobj2)->tzmode, \
1790 (tobj1)->vtm.utc_offset = (tobj2)->vtm.utc_offset, \
1791 (tobj1)->vtm.zone = (tobj2)->vtm.zone)
1792
1793static int zone_localtime(VALUE zone, VALUE time);
1794static VALUE time_get_tm(VALUE, struct time_object *);
1795#define MAKE_TM(time, tobj) \
1796 do { \
1797 if ((tobj)->tm_got == 0) { \
1798 time_get_tm((time), (tobj)); \
1799 } \
1800 } while (0)
1801#define MAKE_TM_ENSURE(time, tobj, cond) \
1802 do { \
1803 MAKE_TM(time, tobj); \
1804 if (!(cond)) { \
1805 force_make_tm(time, tobj); \
1806 } \
1807 } while (0)
1808
1809static inline void
1810force_make_tm(VALUE time, struct time_object *tobj)
1811{
1812 VALUE zone = tobj->vtm.zone;
1813 if (!NIL_P(zone) && zone != str_empty && zone != str_utc) {
1814 if (zone_localtime(zone, time)) return;
1815 }
1816 tobj->tm_got = 0;
1817 time_get_tm(time, tobj);
1818}
1819
1820static void
1821time_mark(void *ptr)
1822{
1823 struct time_object *tobj = ptr;
1824 if (!FIXWV_P(tobj->timew))
1825 rb_gc_mark(w2v(tobj->timew));
1826 rb_gc_mark(tobj->vtm.year);
1827 rb_gc_mark(tobj->vtm.subsecx);
1828 rb_gc_mark(tobj->vtm.utc_offset);
1829 rb_gc_mark(tobj->vtm.zone);
1830}
1831
1832static size_t
1833time_memsize(const void *tobj)
1834{
1835 return sizeof(struct time_object);
1836}
1837
1838static const rb_data_type_t time_data_type = {
1839 "time",
1840 {time_mark, RUBY_TYPED_DEFAULT_FREE, time_memsize,},
1841 0, 0,
1842 (RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE),
1843};
1844
1845static VALUE
1846time_s_alloc(VALUE klass)
1847{
1848 VALUE obj;
1849 struct time_object *tobj;
1850
1851 obj = TypedData_Make_Struct(klass, struct time_object, &time_data_type, tobj);
1852 tobj->tzmode = TIME_TZMODE_UNINITIALIZED;
1853 tobj->tm_got=0;
1854 tobj->timew = WINT2FIXWV(0);
1855 tobj->vtm.zone = Qnil;
1856
1857 return obj;
1858}
1859
1860static struct time_object *
1861get_timeval(VALUE obj)
1862{
1863 struct time_object *tobj;
1864 TypedData_Get_Struct(obj, struct time_object, &time_data_type, tobj);
1865 if (!TIME_INIT_P(tobj)) {
1866 rb_raise(rb_eTypeError, "uninitialized %"PRIsVALUE, rb_obj_class(obj));
1867 }
1868 return tobj;
1869}
1870
1871static struct time_object *
1872get_new_timeval(VALUE obj)
1873{
1874 struct time_object *tobj;
1875 TypedData_Get_Struct(obj, struct time_object, &time_data_type, tobj);
1876 if (TIME_INIT_P(tobj)) {
1877 rb_raise(rb_eTypeError, "already initialized %"PRIsVALUE, rb_obj_class(obj));
1878 }
1879 return tobj;
1880}
1881
1882static void
1883time_modify(VALUE time)
1884{
1885 rb_check_frozen(time);
1886}
1887
1888static wideval_t
1889timenano2timew(time_t sec, long nsec)
1890{
1891 wideval_t timew;
1892
1893 timew = rb_time_magnify(TIMET2WV(sec));
1894 if (nsec)
1895 timew = wadd(timew, wmulquoll(WINT2WV(nsec), TIME_SCALE, 1000000000));
1896 return timew;
1897}
1898
1899static struct timespec
1900timew2timespec(wideval_t timew)
1901{
1902 VALUE subsecx;
1903 struct timespec ts;
1904 wideval_t timew2;
1905
1906 if (timew_out_of_timet_range(timew))
1907 rb_raise(rb_eArgError, "time out of system range");
1908 split_second(timew, &timew2, &subsecx);
1909 ts.tv_sec = WV2TIMET(timew2);
1910 ts.tv_nsec = NUM2LONG(mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE)));
1911 return ts;
1912}
1913
1914static struct timespec *
1915timew2timespec_exact(wideval_t timew, struct timespec *ts)
1916{
1917 VALUE subsecx;
1918 wideval_t timew2;
1919 VALUE nsecv;
1920
1921 if (timew_out_of_timet_range(timew))
1922 return NULL;
1923 split_second(timew, &timew2, &subsecx);
1924 ts->tv_sec = WV2TIMET(timew2);
1925 nsecv = mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE));
1926 if (!FIXNUM_P(nsecv))
1927 return NULL;
1928 ts->tv_nsec = NUM2LONG(nsecv);
1929 return ts;
1930}
1931
1932void
1934{
1935#ifdef HAVE_CLOCK_GETTIME
1936 if (clock_gettime(CLOCK_REALTIME, ts) == -1) {
1937 rb_sys_fail("clock_gettime");
1938 }
1939#else
1940 {
1941 struct timeval tv;
1942 if (gettimeofday(&tv, 0) < 0) {
1943 rb_sys_fail("gettimeofday");
1944 }
1945 ts->tv_sec = tv.tv_sec;
1946 ts->tv_nsec = tv.tv_usec * 1000;
1947 }
1948#endif
1949}
1950
1951static VALUE
1952time_init_now(rb_execution_context_t *ec, VALUE time, VALUE zone)
1953{
1954 struct time_object *tobj;
1955 struct timespec ts;
1956
1957 time_modify(time);
1958 GetNewTimeval(time, tobj);
1959 TZMODE_SET_LOCALTIME(tobj);
1960 tobj->tm_got=0;
1961 tobj->timew = WINT2FIXWV(0);
1962 rb_timespec_now(&ts);
1963 tobj->timew = timenano2timew(ts.tv_sec, ts.tv_nsec);
1964
1965 if (!NIL_P(zone)) {
1966 time_zonelocal(time, zone);
1967 }
1968 return time;
1969}
1970
1971static VALUE
1972time_s_now(rb_execution_context_t *ec, VALUE klass, VALUE zone)
1973{
1974 VALUE t = time_s_alloc(klass);
1975 return time_init_now(ec, t, zone);
1976}
1977
1978static VALUE
1979time_set_utc_offset(VALUE time, VALUE off)
1980{
1981 struct time_object *tobj;
1982 off = num_exact(off);
1983
1984 time_modify(time);
1985 GetTimeval(time, tobj);
1986
1987 tobj->tm_got = 0;
1988 tobj->vtm.zone = Qnil;
1989 TZMODE_SET_FIXOFF(tobj, off);
1990
1991 return time;
1992}
1993
1994static void
1995vtm_add_offset(struct vtm *vtm, VALUE off, int sign)
1996{
1997 VALUE subsec, v;
1998 int sec, min, hour;
1999 int day;
2000
2001 if (lt(off, INT2FIX(0))) {
2002 sign = -sign;
2003 off = neg(off);
2004 }
2005 divmodv(off, INT2FIX(1), &off, &subsec);
2006 divmodv(off, INT2FIX(60), &off, &v);
2007 sec = NUM2INT(v);
2008 divmodv(off, INT2FIX(60), &off, &v);
2009 min = NUM2INT(v);
2010 divmodv(off, INT2FIX(24), &off, &v);
2011 hour = NUM2INT(v);
2012
2013 if (sign < 0) {
2014 subsec = neg(subsec);
2015 sec = -sec;
2016 min = -min;
2017 hour = -hour;
2018 }
2019
2020 day = 0;
2021
2022 if (!rb_equal(subsec, INT2FIX(0))) {
2023 vtm->subsecx = addv(vtm->subsecx, w2v(rb_time_magnify(v2w(subsec))));
2024 if (lt(vtm->subsecx, INT2FIX(0))) {
2025 vtm->subsecx = addv(vtm->subsecx, INT2FIX(TIME_SCALE));
2026 sec -= 1;
2027 }
2028 if (le(INT2FIX(TIME_SCALE), vtm->subsecx)) {
2029 vtm->subsecx = subv(vtm->subsecx, INT2FIX(TIME_SCALE));
2030 sec += 1;
2031 }
2032 }
2033 if (sec) {
2034 /* If sec + subsec == 0, don't change vtm->sec.
2035 * It may be 60 which is a leap second. */
2036 sec += vtm->sec;
2037 if (sec < 0) {
2038 sec += 60;
2039 min -= 1;
2040 }
2041 if (60 <= sec) {
2042 sec -= 60;
2043 min += 1;
2044 }
2045 vtm->sec = sec;
2046 }
2047 if (min) {
2048 min += vtm->min;
2049 if (min < 0) {
2050 min += 60;
2051 hour -= 1;
2052 }
2053 if (60 <= min) {
2054 min -= 60;
2055 hour += 1;
2056 }
2057 vtm->min = min;
2058 }
2059 if (hour) {
2060 hour += vtm->hour;
2061 if (hour < 0) {
2062 hour += 24;
2063 day = -1;
2064 }
2065 if (24 <= hour) {
2066 hour -= 24;
2067 day = 1;
2068 }
2069 vtm->hour = hour;
2070 }
2071
2072 vtm_add_day(vtm, day);
2073}
2074
2075static void
2076vtm_add_day(struct vtm *vtm, int day)
2077{
2078 if (day) {
2079 if (day < 0) {
2080 if (vtm->mon == 1 && vtm->mday == 1) {
2081 vtm->mday = 31;
2082 vtm->mon = 12; /* December */
2083 vtm->year = subv(vtm->year, INT2FIX(1));
2084 if (vtm->yday != 0)
2085 vtm->yday = leap_year_v_p(vtm->year) ? 366 : 365;
2086 }
2087 else if (vtm->mday == 1) {
2088 const int8_t *days_in_month = days_in_month_in_v(vtm->year);
2089 vtm->mon--;
2090 vtm->mday = days_in_month[vtm->mon-1];
2091 if (vtm->yday != 0) vtm->yday--;
2092 }
2093 else {
2094 vtm->mday--;
2095 if (vtm->yday != 0) vtm->yday--;
2096 }
2097 if (vtm->wday != VTM_WDAY_INITVAL) vtm->wday = (vtm->wday + 6) % 7;
2098 }
2099 else {
2100 int leap = leap_year_v_p(vtm->year);
2101 if (vtm->mon == 12 && vtm->mday == 31) {
2102 vtm->year = addv(vtm->year, INT2FIX(1));
2103 vtm->mon = 1; /* January */
2104 vtm->mday = 1;
2105 vtm->yday = 1;
2106 }
2107 else if (vtm->mday == days_in_month_of(leap)[vtm->mon-1]) {
2108 vtm->mon++;
2109 vtm->mday = 1;
2110 if (vtm->yday != 0) vtm->yday++;
2111 }
2112 else {
2113 vtm->mday++;
2114 if (vtm->yday != 0) vtm->yday++;
2115 }
2116 if (vtm->wday != VTM_WDAY_INITVAL) vtm->wday = (vtm->wday + 1) % 7;
2117 }
2118 }
2119}
2120
2121static int
2122maybe_tzobj_p(VALUE obj)
2123{
2124 if (NIL_P(obj)) return FALSE;
2125 if (RB_INTEGER_TYPE_P(obj)) return FALSE;
2126 if (RB_TYPE_P(obj, T_STRING)) return FALSE;
2127 return TRUE;
2128}
2129
2130NORETURN(static void invalid_utc_offset(VALUE));
2131static void
2132invalid_utc_offset(VALUE zone)
2133{
2134 rb_raise(rb_eArgError, "\"+HH:MM\", \"-HH:MM\", \"UTC\" or "
2135 "\"A\"..\"I\",\"K\"..\"Z\" expected for utc_offset: %"PRIsVALUE,
2136 zone);
2137}
2138
2139static VALUE
2140utc_offset_arg(VALUE arg)
2141{
2142 VALUE tmp;
2143 if (!NIL_P(tmp = rb_check_string_type(arg))) {
2144 int n = 0;
2145 const char *s = RSTRING_PTR(tmp), *min = NULL, *sec = NULL;
2146 if (!rb_enc_str_asciicompat_p(tmp)) {
2147 goto invalid_utc_offset;
2148 }
2149 switch (RSTRING_LEN(tmp)) {
2150 case 1:
2151 if (s[0] == 'Z') {
2152 return UTC_ZONE;
2153 }
2154 /* Military Time Zone Names */
2155 if (s[0] >= 'A' && s[0] <= 'I') {
2156 n = (int)s[0] - 'A' + 1;
2157 }
2158 /* No 'J' zone */
2159 else if (s[0] >= 'K' && s[0] <= 'M') {
2160 n = (int)s[0] - 'A';
2161 }
2162 else if (s[0] >= 'N' && s[0] <= 'Y') {
2163 n = 'M' - (int)s[0];
2164 }
2165 else {
2166 goto invalid_utc_offset;
2167 }
2168 n *= 3600;
2169 return INT2FIX(n);
2170 case 3:
2171 if (STRNCASECMP("UTC", s, 3) == 0) {
2172 return UTC_ZONE;
2173 }
2174 break; /* +HH */
2175 case 7: /* +HHMMSS */
2176 sec = s+5;
2177 /* fallthrough */
2178 case 5: /* +HHMM */
2179 min = s+3;
2180 break;
2181 case 9: /* +HH:MM:SS */
2182 if (s[6] != ':') goto invalid_utc_offset;
2183 sec = s+7;
2184 /* fallthrough */
2185 case 6: /* +HH:MM */
2186 if (s[3] != ':') goto invalid_utc_offset;
2187 min = s+4;
2188 break;
2189 default:
2190 goto invalid_utc_offset;
2191 }
2192 if (sec) {
2193 if (!ISDIGIT(sec[0]) || !ISDIGIT(sec[1])) goto invalid_utc_offset;
2194 n += (sec[0] * 10 + sec[1] - '0' * 11);
2195 ASSUME(min);
2196 }
2197 if (min) {
2198 if (!ISDIGIT(min[0]) || !ISDIGIT(min[1])) goto invalid_utc_offset;
2199 if (min[0] > '5') goto invalid_utc_offset;
2200 n += (min[0] * 10 + min[1] - '0' * 11) * 60;
2201 }
2202 if (s[0] != '+' && s[0] != '-') goto invalid_utc_offset;
2203 if (!ISDIGIT(s[1]) || !ISDIGIT(s[2])) goto invalid_utc_offset;
2204 n += (s[1] * 10 + s[2] - '0' * 11) * 3600;
2205 if (s[0] == '-') {
2206 if (n == 0) return UTC_ZONE;
2207 n = -n;
2208 }
2209 return INT2FIX(n);
2210 }
2211 else {
2212 return num_exact(arg);
2213 }
2214 invalid_utc_offset:
2215 return Qnil;
2216}
2217
2218static void
2219zone_set_offset(VALUE zone, struct time_object *tobj,
2220 wideval_t tlocal, wideval_t tutc)
2221{
2222 /* tlocal and tutc must be unmagnified and in seconds */
2223 wideval_t w = wsub(tlocal, tutc);
2224 VALUE off = w2v(w);
2225 validate_utc_offset(off);
2226 tobj->vtm.utc_offset = off;
2227 tobj->vtm.zone = zone;
2228 TZMODE_SET_LOCALTIME(tobj);
2229}
2230
2231static wideval_t
2232extract_time(VALUE time)
2233{
2234 wideval_t t;
2235 const ID id_to_i = idTo_i;
2236
2237#define EXTRACT_TIME() do { \
2238 t = v2w(rb_Integer(AREF(to_i))); \
2239 } while (0)
2240
2241 if (rb_typeddata_is_kind_of(time, &time_data_type)) {
2242 struct time_object *tobj = DATA_PTR(time);
2243
2244 time_gmtime(time); /* ensure tm got */
2245 t = rb_time_unmagnify(tobj->timew);
2246 }
2247 else if (RB_TYPE_P(time, T_STRUCT)) {
2248#define AREF(x) rb_struct_aref(time, ID2SYM(id_##x))
2249 EXTRACT_TIME();
2250#undef AREF
2251 }
2252 else {
2253#define AREF(x) rb_funcallv(time, id_##x, 0, 0)
2254 EXTRACT_TIME();
2255#undef AREF
2256 }
2257#undef EXTRACT_TIME
2258
2259 return t;
2260}
2261
2262static wideval_t
2263extract_vtm(VALUE time, struct vtm *vtm, VALUE subsecx)
2264{
2265 wideval_t t;
2266 const ID id_to_i = idTo_i;
2267
2268#define EXTRACT_VTM() do { \
2269 VALUE subsecx; \
2270 vtm->year = obj2vint(AREF(year)); \
2271 vtm->mon = month_arg(AREF(mon)); \
2272 vtm->mday = obj2ubits(AREF(mday), 5); \
2273 vtm->hour = obj2ubits(AREF(hour), 5); \
2274 vtm->min = obj2ubits(AREF(min), 6); \
2275 vtm->sec = obj2subsecx(AREF(sec), &subsecx); \
2276 vtm->isdst = RTEST(AREF(isdst)); \
2277 vtm->utc_offset = Qnil; \
2278 t = v2w(rb_Integer(AREF(to_i))); \
2279 } while (0)
2280
2281 if (rb_typeddata_is_kind_of(time, &time_data_type)) {
2282 struct time_object *tobj = DATA_PTR(time);
2283
2284 time_get_tm(time, tobj);
2285 *vtm = tobj->vtm;
2286 t = rb_time_unmagnify(tobj->timew);
2287 if (TZMODE_FIXOFF_P(tobj) && vtm->utc_offset != INT2FIX(0))
2288 t = wadd(t, v2w(vtm->utc_offset));
2289 }
2290 else if (RB_TYPE_P(time, T_STRUCT)) {
2291#define AREF(x) rb_struct_aref(time, ID2SYM(id_##x))
2292 EXTRACT_VTM();
2293#undef AREF
2294 }
2295 else if (rb_integer_type_p(time)) {
2296 t = v2w(time);
2297 GMTIMEW(rb_time_magnify(t), vtm);
2298 }
2299 else {
2300#define AREF(x) rb_funcallv(time, id_##x, 0, 0)
2301 EXTRACT_VTM();
2302#undef AREF
2303 }
2304#undef EXTRACT_VTM
2305 vtm->subsecx = subsecx;
2306 validate_vtm(vtm);
2307 return t;
2308}
2309
2310static void
2311zone_set_dst(VALUE zone, struct time_object *tobj, VALUE tm)
2312{
2313 ID id_dst_p;
2314 VALUE dst;
2315 CONST_ID(id_dst_p, "dst?");
2316 dst = rb_check_funcall(zone, id_dst_p, 1, &tm);
2317 tobj->vtm.isdst = (!UNDEF_P(dst) && RTEST(dst));
2318}
2319
2320static int
2321zone_timelocal(VALUE zone, VALUE time)
2322{
2323 VALUE utc, tm;
2324 struct time_object *tobj = DATA_PTR(time);
2325 wideval_t t, s;
2326
2327 t = rb_time_unmagnify(tobj->timew);
2328 tm = tm_from_time(rb_cTimeTM, time);
2329 utc = rb_check_funcall(zone, id_local_to_utc, 1, &tm);
2330 if (UNDEF_P(utc)) return 0;
2331
2332 s = extract_time(utc);
2333 zone_set_offset(zone, tobj, t, s);
2334 s = rb_time_magnify(s);
2335 if (tobj->vtm.subsecx != INT2FIX(0)) {
2336 s = wadd(s, v2w(tobj->vtm.subsecx));
2337 }
2338 tobj->timew = s;
2339 zone_set_dst(zone, tobj, tm);
2340 return 1;
2341}
2342
2343static int
2344zone_localtime(VALUE zone, VALUE time)
2345{
2346 VALUE local, tm, subsecx;
2347 struct time_object *tobj = DATA_PTR(time);
2348 wideval_t t, s;
2349
2350 split_second(tobj->timew, &t, &subsecx);
2351 tm = tm_from_time(rb_cTimeTM, time);
2352
2353 local = rb_check_funcall(zone, id_utc_to_local, 1, &tm);
2354 if (UNDEF_P(local)) return 0;
2355
2356 s = extract_vtm(local, &tobj->vtm, subsecx);
2357 tobj->tm_got = 1;
2358 zone_set_offset(zone, tobj, s, t);
2359 zone_set_dst(zone, tobj, tm);
2360 return 1;
2361}
2362
2363static VALUE
2364find_timezone(VALUE time, VALUE zone)
2365{
2366 VALUE klass = CLASS_OF(time);
2367
2368 return rb_check_funcall_default(klass, id_find_timezone, 1, &zone, Qnil);
2369}
2370
2371/* Turn the special case 24:00:00 of already validated vtm into
2372 * 00:00:00 the next day */
2373static void
2374vtm_day_wraparound(struct vtm *vtm)
2375{
2376 if (vtm->hour < 24) return;
2377
2378 /* Assuming UTC and no care of DST, just reset hour and advance
2379 * date, not to discard the validated vtm. */
2380 vtm->hour = 0;
2381 vtm_add_day(vtm, 1);
2382}
2383
2384static VALUE time_init_vtm(VALUE time, struct vtm vtm, VALUE zone);
2385
2386static VALUE
2387time_init_args(rb_execution_context_t *ec, VALUE time, VALUE year, VALUE mon, VALUE mday,
2388 VALUE hour, VALUE min, VALUE sec, VALUE zone)
2389{
2390 struct vtm vtm;
2391
2392 vtm.wday = VTM_WDAY_INITVAL;
2393 vtm.yday = 0;
2394 vtm.zone = str_empty;
2395
2396 vtm.year = obj2vint(year);
2397
2398 vtm.mon = NIL_P(mon) ? 1 : month_arg(mon);
2399
2400 vtm.mday = NIL_P(mday) ? 1 : obj2ubits(mday, 5);
2401
2402 vtm.hour = NIL_P(hour) ? 0 : obj2ubits(hour, 5);
2403
2404 vtm.min = NIL_P(min) ? 0 : obj2ubits(min, 6);
2405
2406 if (NIL_P(sec)) {
2407 vtm.sec = 0;
2408 vtm.subsecx = INT2FIX(0);
2409 }
2410 else {
2411 VALUE subsecx;
2412 vtm.sec = obj2subsecx(sec, &subsecx);
2413 vtm.subsecx = subsecx;
2414 }
2415
2416 return time_init_vtm(time, vtm, zone);
2417}
2418
2419static VALUE
2420time_init_vtm(VALUE time, struct vtm vtm, VALUE zone)
2421{
2422 VALUE utc = Qnil;
2423 struct time_object *tobj;
2424
2425 vtm.isdst = VTM_ISDST_INITVAL;
2426 vtm.utc_offset = Qnil;
2427 const VALUE arg = zone;
2428 if (!NIL_P(arg)) {
2429 zone = Qnil;
2430 if (arg == ID2SYM(rb_intern("dst")))
2431 vtm.isdst = 1;
2432 else if (arg == ID2SYM(rb_intern("std")))
2433 vtm.isdst = 0;
2434 else if (maybe_tzobj_p(arg))
2435 zone = arg;
2436 else if (!NIL_P(utc = utc_offset_arg(arg)))
2437 vtm.utc_offset = utc == UTC_ZONE ? INT2FIX(0) : utc;
2438 else if (NIL_P(zone = find_timezone(time, arg)))
2439 invalid_utc_offset(arg);
2440 }
2441
2442 validate_vtm(&vtm);
2443
2444 time_modify(time);
2445 GetNewTimeval(time, tobj);
2446
2447 if (!NIL_P(zone)) {
2448 tobj->timew = timegmw(&vtm);
2449 vtm_day_wraparound(&vtm);
2450 tobj->vtm = vtm;
2451 tobj->tm_got = 1;
2452 TZMODE_SET_LOCALTIME(tobj);
2453 if (zone_timelocal(zone, time)) {
2454 return time;
2455 }
2456 else if (NIL_P(vtm.utc_offset = utc_offset_arg(zone))) {
2457 if (NIL_P(zone = find_timezone(time, zone)) || !zone_timelocal(zone, time))
2458 invalid_utc_offset(arg);
2459 }
2460 }
2461
2462 if (utc == UTC_ZONE) {
2463 tobj->timew = timegmw(&vtm);
2464 vtm.isdst = 0; /* No DST in UTC */
2465 vtm_day_wraparound(&vtm);
2466 tobj->vtm = vtm;
2467 tobj->tm_got = 1;
2468 TZMODE_SET_UTC(tobj);
2469 return time;
2470 }
2471
2472 TZMODE_SET_LOCALTIME(tobj);
2473 tobj->tm_got=0;
2474 tobj->timew = WINT2FIXWV(0);
2475
2476 if (!NIL_P(vtm.utc_offset)) {
2477 VALUE off = vtm.utc_offset;
2478 vtm_add_offset(&vtm, off, -1);
2479 vtm.utc_offset = Qnil;
2480 tobj->timew = timegmw(&vtm);
2481 return time_set_utc_offset(time, off);
2482 }
2483 else {
2484 tobj->timew = timelocalw(&vtm);
2485 return time_localtime(time);
2486 }
2487}
2488
2489static int
2490two_digits(const char *ptr, const char *end, const char **endp, const char *name)
2491{
2492 ssize_t len = end - ptr;
2493 if (len < 2 || (!ISDIGIT(ptr[0]) || !ISDIGIT(ptr[1])) ||
2494 ((len > 2) && ISDIGIT(ptr[2]))) {
2495 VALUE mesg = rb_sprintf("two digits %s is expected", name);
2496 if (ptr[-1] == '-' || ptr[-1] == ':') {
2497 rb_str_catf(mesg, " after `%c'", ptr[-1]);
2498 }
2499 rb_str_catf(mesg, ": %.*s", ((len > 10) ? 10 : (int)(end - ptr)) + 1, ptr - 1);
2501 }
2502 *endp = ptr + 2;
2503 return (ptr[0] - '0') * 10 + (ptr[1] - '0');
2504}
2505
2506static VALUE
2507parse_int(const char *ptr, const char *end, const char **endp, size_t *ndigits, bool sign)
2508{
2509 ssize_t len = (end - ptr);
2510 int flags = sign ? RB_INT_PARSE_SIGN : 0;
2511 return rb_int_parse_cstr(ptr, len, (char **)endp, ndigits, 10, flags);
2512}
2513
2514static VALUE
2515time_init_parse(rb_execution_context_t *ec, VALUE klass, VALUE str, VALUE zone, VALUE precision)
2516{
2517 if (NIL_P(str = rb_check_string_type(str))) return Qnil;
2518 if (!rb_enc_str_asciicompat_p(str)) {
2519 rb_raise(rb_eArgError, "time string should have ASCII compatible encoding");
2520 }
2521
2522 const char *const begin = RSTRING_PTR(str);
2523 const char *const end = RSTRING_END(str);
2524 const char *ptr = begin;
2525 VALUE year = Qnil, subsec = Qnil;
2526 int mon = -1, mday = -1, hour = -1, min = -1, sec = -1;
2527 size_t ndigits;
2528 size_t prec = NIL_P(precision) ? SIZE_MAX : NUM2SIZET(precision);
2529
2530 while ((ptr < end) && ISSPACE(*ptr)) ptr++;
2531 year = parse_int(ptr, end, &ptr, &ndigits, true);
2532 if (NIL_P(year)) {
2533 rb_raise(rb_eArgError, "can't parse: %+"PRIsVALUE, str);
2534 }
2535 else if (ndigits < 4) {
2536 rb_raise(rb_eArgError, "year must be 4 or more digits: %.*s", (int)ndigits, ptr - ndigits);
2537 }
2538 do {
2539#define peekable_p(n) ((ptrdiff_t)(n) < (end - ptr))
2540#define peek_n(c, n) (peekable_p(n) && ((unsigned char)ptr[n] == (c)))
2541#define peek(c) peek_n(c, 0)
2542#define peekc_n(n) (peekable_p(n) ? (int)(unsigned char)ptr[n] : -1)
2543#define peekc() peekc_n(0)
2544#define expect_two_digits(x, bits) \
2545 (((unsigned int)(x = two_digits(ptr + 1, end, &ptr, #x)) > (1U << bits) - 1) ? \
2546 rb_raise(rb_eArgError, #x" out of range") : (void)0)
2547 if (!peek('-')) break;
2548 expect_two_digits(mon, 4);
2549 if (!peek('-')) break;
2550 expect_two_digits(mday, 5);
2551 if (!peek(' ') && !peek('T')) break;
2552 const char *const time_part = ptr + 1;
2553 if (!ISDIGIT(peekc_n(1))) break;
2554#define nofraction(x) \
2555 if (peek('.')) { \
2556 rb_raise(rb_eArgError, "fraction " #x " is not supported: %.*s", \
2557 (int)(ptr + 1 - time_part), time_part); \
2558 }
2559#define need_colon(x) \
2560 if (!peek(':')) { \
2561 rb_raise(rb_eArgError, "missing " #x " part: %.*s", \
2562 (int)(ptr + 1 - time_part), time_part); \
2563 }
2564 expect_two_digits(hour, 5);
2565 nofraction(hour);
2566 need_colon(min);
2567 expect_two_digits(min, 6);
2568 nofraction(min);
2569 need_colon(sec);
2570 expect_two_digits(sec, 6);
2571 if (peek('.')) {
2572 ptr++;
2573 for (ndigits = 0; ndigits < prec && ISDIGIT(peekc_n(ndigits)); ++ndigits);
2574 if (!ndigits) {
2575 int clen = rb_enc_precise_mbclen(ptr, end, rb_enc_get(str));
2576 if (clen < 0) clen = 0;
2577 rb_raise(rb_eArgError, "subsecond expected after dot: %.*s",
2578 (int)(ptr - time_part) + clen, time_part);
2579 }
2580 subsec = parse_int(ptr, ptr + ndigits, &ptr, &ndigits, false);
2581 if (NIL_P(subsec)) break;
2582 while (ptr < end && ISDIGIT(*ptr)) ptr++;
2583 }
2584 } while (0);
2585 while (ptr < end && ISSPACE(*ptr)) ptr++;
2586 const char *const zstr = ptr;
2587 while (ptr < end && !ISSPACE(*ptr)) ptr++;
2588 const char *const zend = ptr;
2589 while (ptr < end && ISSPACE(*ptr)) ptr++;
2590 if (ptr < end) {
2591 VALUE mesg = rb_str_new_cstr("can't parse at: ");
2592 rb_str_cat(mesg, ptr, end - ptr);
2594 }
2595 if (zend > zstr) {
2596 zone = rb_str_subseq(str, zstr - begin, zend - zstr);
2597 }
2598 if (!NIL_P(subsec)) {
2599 /* subseconds is the last using ndigits */
2600 static const size_t TIME_SCALE_NUMDIGITS =
2601 /* TIME_SCALE should be 10000... */
2602 rb_strlen_lit(STRINGIZE(TIME_SCALE)) - 1;
2603
2604 if (ndigits < TIME_SCALE_NUMDIGITS) {
2605 VALUE mul = rb_int_positive_pow(10, TIME_SCALE_NUMDIGITS - ndigits);
2606 subsec = rb_int_mul(subsec, mul);
2607 }
2608 else if (ndigits > TIME_SCALE_NUMDIGITS) {
2609 VALUE num = rb_int_positive_pow(10, ndigits - TIME_SCALE_NUMDIGITS);
2610 subsec = rb_rational_new(subsec, num);
2611 }
2612 }
2613
2614 struct vtm vtm = {
2615 .wday = VTM_WDAY_INITVAL,
2616 .yday = 0,
2617 .zone = str_empty,
2618 .year = year,
2619 .mon = (mon < 0) ? 1 : mon,
2620 .mday = (mday < 0) ? 1 : mday,
2621 .hour = (hour < 0) ? 0 : hour,
2622 .min = (min < 0) ? 0 : min,
2623 .sec = (sec < 0) ? 0 : sec,
2624 .subsecx = NIL_P(subsec) ? INT2FIX(0) : subsec,
2625 };
2626 return time_init_vtm(klass, vtm, zone);
2627}
2628
2629static void
2630subsec_normalize(time_t *secp, long *subsecp, const long maxsubsec)
2631{
2632 time_t sec = *secp;
2633 long subsec = *subsecp;
2634 long sec2;
2635
2636 if (UNLIKELY(subsec >= maxsubsec)) { /* subsec positive overflow */
2637 sec2 = subsec / maxsubsec;
2638 if (TIMET_MAX - sec2 < sec) {
2639 rb_raise(rb_eRangeError, "out of Time range");
2640 }
2641 subsec -= sec2 * maxsubsec;
2642 sec += sec2;
2643 }
2644 else if (UNLIKELY(subsec < 0)) { /* subsec negative overflow */
2645 sec2 = NDIV(subsec, maxsubsec); /* negative div */
2646 if (sec < TIMET_MIN - sec2) {
2647 rb_raise(rb_eRangeError, "out of Time range");
2648 }
2649 subsec -= sec2 * maxsubsec;
2650 sec += sec2;
2651 }
2652#ifndef NEGATIVE_TIME_T
2653 if (sec < 0)
2654 rb_raise(rb_eArgError, "time must be positive");
2655#endif
2656 *secp = sec;
2657 *subsecp = subsec;
2658}
2659
2660#define time_usec_normalize(secp, usecp) subsec_normalize(secp, usecp, 1000000)
2661#define time_nsec_normalize(secp, nsecp) subsec_normalize(secp, nsecp, 1000000000)
2662
2663static wideval_t
2664nsec2timew(time_t sec, long nsec)
2665{
2666 time_nsec_normalize(&sec, &nsec);
2667 return timenano2timew(sec, nsec);
2668}
2669
2670static VALUE
2671time_new_timew(VALUE klass, wideval_t timew)
2672{
2673 VALUE time = time_s_alloc(klass);
2674 struct time_object *tobj;
2675
2676 tobj = DATA_PTR(time); /* skip type check */
2677 TZMODE_SET_LOCALTIME(tobj);
2678 tobj->timew = timew;
2679
2680 return time;
2681}
2682
2683VALUE
2684rb_time_new(time_t sec, long usec)
2685{
2686 time_usec_normalize(&sec, &usec);
2687 return time_new_timew(rb_cTime, timenano2timew(sec, usec * 1000));
2688}
2689
2690/* returns localtime time object */
2691VALUE
2692rb_time_nano_new(time_t sec, long nsec)
2693{
2694 return time_new_timew(rb_cTime, nsec2timew(sec, nsec));
2695}
2696
2697VALUE
2698rb_time_timespec_new(const struct timespec *ts, int offset)
2699{
2700 struct time_object *tobj;
2701 VALUE time = time_new_timew(rb_cTime, nsec2timew(ts->tv_sec, ts->tv_nsec));
2702
2703 if (-86400 < offset && offset < 86400) { /* fixoff */
2704 GetTimeval(time, tobj);
2705 TZMODE_SET_FIXOFF(tobj, INT2FIX(offset));
2706 }
2707 else if (offset == INT_MAX) { /* localtime */
2708 }
2709 else if (offset == INT_MAX-1) { /* UTC */
2710 GetTimeval(time, tobj);
2711 TZMODE_SET_UTC(tobj);
2712 }
2713 else {
2714 rb_raise(rb_eArgError, "utc_offset out of range");
2715 }
2716
2717 return time;
2718}
2719
2720VALUE
2722{
2723 VALUE time = time_new_timew(rb_cTime, rb_time_magnify(v2w(timev)));
2724
2725 if (!NIL_P(off)) {
2726 VALUE zone = off;
2727
2728 if (maybe_tzobj_p(zone)) {
2729 time_gmtime(time);
2730 if (zone_timelocal(zone, time)) return time;
2731 }
2732 if (NIL_P(off = utc_offset_arg(off))) {
2733 off = zone;
2734 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
2735 time_gmtime(time);
2736 if (!zone_timelocal(zone, time)) invalid_utc_offset(off);
2737 return time;
2738 }
2739 else if (off == UTC_ZONE) {
2740 return time_gmtime(time);
2741 }
2742
2743 validate_utc_offset(off);
2744 time_set_utc_offset(time, off);
2745 return time;
2746 }
2747
2748 return time;
2749}
2750
2751static struct timespec
2752time_timespec(VALUE num, int interval)
2753{
2754 struct timespec t;
2755 const char *const tstr = interval ? "time interval" : "time";
2756 VALUE i, f, ary;
2757
2758#ifndef NEGATIVE_TIME_T
2759# define arg_range_check(v) \
2760 (((v) < 0) ? \
2761 rb_raise(rb_eArgError, "%s must not be negative", tstr) : \
2762 (void)0)
2763#else
2764# define arg_range_check(v) \
2765 ((interval && (v) < 0) ? \
2766 rb_raise(rb_eArgError, "time interval must not be negative") : \
2767 (void)0)
2768#endif
2769
2770 if (FIXNUM_P(num)) {
2771 t.tv_sec = NUM2TIMET(num);
2772 arg_range_check(t.tv_sec);
2773 t.tv_nsec = 0;
2774 }
2775 else if (RB_FLOAT_TYPE_P(num)) {
2776 double x = RFLOAT_VALUE(num);
2777 arg_range_check(x);
2778 {
2779 double f, d;
2780
2781 d = modf(x, &f);
2782 if (d >= 0) {
2783 t.tv_nsec = (int)(d*1e9+0.5);
2784 if (t.tv_nsec >= 1000000000) {
2785 t.tv_nsec -= 1000000000;
2786 f += 1;
2787 }
2788 }
2789 else if ((t.tv_nsec = (int)(-d*1e9+0.5)) > 0) {
2790 t.tv_nsec = 1000000000 - t.tv_nsec;
2791 f -= 1;
2792 }
2793 t.tv_sec = (time_t)f;
2794 if (f != t.tv_sec) {
2795 rb_raise(rb_eRangeError, "%f out of Time range", x);
2796 }
2797 }
2798 }
2799 else if (RB_BIGNUM_TYPE_P(num)) {
2800 t.tv_sec = NUM2TIMET(num);
2801 arg_range_check(t.tv_sec);
2802 t.tv_nsec = 0;
2803 }
2804 else {
2805 i = INT2FIX(1);
2806 ary = rb_check_funcall(num, id_divmod, 1, &i);
2807 if (!UNDEF_P(ary) && !NIL_P(ary = rb_check_array_type(ary))) {
2808 i = rb_ary_entry(ary, 0);
2809 f = rb_ary_entry(ary, 1);
2810 t.tv_sec = NUM2TIMET(i);
2811 arg_range_check(t.tv_sec);
2812 f = rb_funcall(f, '*', 1, INT2FIX(1000000000));
2813 t.tv_nsec = NUM2LONG(f);
2814 }
2815 else {
2816 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into %s",
2817 rb_obj_class(num), tstr);
2818 }
2819 }
2820 return t;
2821#undef arg_range_check
2822}
2823
2824static struct timeval
2825time_timeval(VALUE num, int interval)
2826{
2827 struct timespec ts;
2828 struct timeval tv;
2829
2830 ts = time_timespec(num, interval);
2831 tv.tv_sec = (TYPEOF_TIMEVAL_TV_SEC)ts.tv_sec;
2832 tv.tv_usec = (TYPEOF_TIMEVAL_TV_USEC)(ts.tv_nsec / 1000);
2833
2834 return tv;
2835}
2836
2837struct timeval
2839{
2840 return time_timeval(num, TRUE);
2841}
2842
2843struct timeval
2845{
2846 struct time_object *tobj;
2847 struct timeval t;
2848 struct timespec ts;
2849
2850 if (IsTimeval(time)) {
2851 GetTimeval(time, tobj);
2852 ts = timew2timespec(tobj->timew);
2853 t.tv_sec = (TYPEOF_TIMEVAL_TV_SEC)ts.tv_sec;
2854 t.tv_usec = (TYPEOF_TIMEVAL_TV_USEC)(ts.tv_nsec / 1000);
2855 return t;
2856 }
2857 return time_timeval(time, FALSE);
2858}
2859
2860struct timespec
2862{
2863 struct time_object *tobj;
2864 struct timespec t;
2865
2866 if (IsTimeval(time)) {
2867 GetTimeval(time, tobj);
2868 t = timew2timespec(tobj->timew);
2869 return t;
2870 }
2871 return time_timespec(time, FALSE);
2872}
2873
2874struct timespec
2876{
2877 return time_timespec(num, TRUE);
2878}
2879
2880static int
2881get_scale(VALUE unit)
2882{
2883 if (unit == ID2SYM(id_nanosecond) || unit == ID2SYM(id_nsec)) {
2884 return 1000000000;
2885 }
2886 else if (unit == ID2SYM(id_microsecond) || unit == ID2SYM(id_usec)) {
2887 return 1000000;
2888 }
2889 else if (unit == ID2SYM(id_millisecond)) {
2890 return 1000;
2891 }
2892 else {
2893 rb_raise(rb_eArgError, "unexpected unit: %"PRIsVALUE, unit);
2894 }
2895}
2896
2897static VALUE
2898time_s_at(rb_execution_context_t *ec, VALUE klass, VALUE time, VALUE subsec, VALUE unit, VALUE zone)
2899{
2900 VALUE t;
2901 wideval_t timew;
2902
2903 if (subsec) {
2904 int scale = get_scale(unit);
2905 time = num_exact(time);
2906 t = num_exact(subsec);
2907 timew = wadd(rb_time_magnify(v2w(time)), wmulquoll(v2w(t), TIME_SCALE, scale));
2908 t = time_new_timew(klass, timew);
2909 }
2910 else if (IsTimeval(time)) {
2911 struct time_object *tobj, *tobj2;
2912 GetTimeval(time, tobj);
2913 t = time_new_timew(klass, tobj->timew);
2914 GetTimeval(t, tobj2);
2915 TZMODE_COPY(tobj2, tobj);
2916 }
2917 else {
2918 timew = rb_time_magnify(v2w(num_exact(time)));
2919 t = time_new_timew(klass, timew);
2920 }
2921 if (!NIL_P(zone)) {
2922 time_zonelocal(t, zone);
2923 }
2924
2925 return t;
2926}
2927
2928static VALUE
2929time_s_at1(rb_execution_context_t *ec, VALUE klass, VALUE time)
2930{
2931 return time_s_at(ec, klass, time, Qfalse, ID2SYM(id_microsecond), Qnil);
2932}
2933
2934static const char months[][4] = {
2935 "jan", "feb", "mar", "apr", "may", "jun",
2936 "jul", "aug", "sep", "oct", "nov", "dec",
2937};
2938
2939static int
2940obj2int(VALUE obj)
2941{
2942 if (RB_TYPE_P(obj, T_STRING)) {
2943 obj = rb_str_to_inum(obj, 10, TRUE);
2944 }
2945
2946 return NUM2INT(obj);
2947}
2948
2949/* bits should be 0 <= x <= 31 */
2950static uint32_t
2951obj2ubits(VALUE obj, unsigned int bits)
2952{
2953 const unsigned int usable_mask = (1U << bits) - 1;
2954 unsigned int rv = (unsigned int)obj2int(obj);
2955
2956 if ((rv & usable_mask) != rv)
2957 rb_raise(rb_eArgError, "argument out of range");
2958 return (uint32_t)rv;
2959}
2960
2961static VALUE
2962obj2vint(VALUE obj)
2963{
2964 if (RB_TYPE_P(obj, T_STRING)) {
2965 obj = rb_str_to_inum(obj, 10, TRUE);
2966 }
2967 else {
2968 obj = rb_to_int(obj);
2969 }
2970
2971 return obj;
2972}
2973
2974static uint32_t
2975obj2subsecx(VALUE obj, VALUE *subsecx)
2976{
2977 VALUE subsec;
2978
2979 if (RB_TYPE_P(obj, T_STRING)) {
2980 obj = rb_str_to_inum(obj, 10, TRUE);
2981 *subsecx = INT2FIX(0);
2982 }
2983 else {
2984 divmodv(num_exact(obj), INT2FIX(1), &obj, &subsec);
2985 *subsecx = w2v(rb_time_magnify(v2w(subsec)));
2986 }
2987 return obj2ubits(obj, 6); /* vtm->sec */
2988}
2989
2990static VALUE
2991usec2subsecx(VALUE obj)
2992{
2993 if (RB_TYPE_P(obj, T_STRING)) {
2994 obj = rb_str_to_inum(obj, 10, TRUE);
2995 }
2996
2997 return mulquov(num_exact(obj), INT2FIX(TIME_SCALE), INT2FIX(1000000));
2998}
2999
3000static uint32_t
3001month_arg(VALUE arg)
3002{
3003 int i, mon;
3004
3005 if (FIXNUM_P(arg)) {
3006 return obj2ubits(arg, 4);
3007 }
3008
3009 mon = 0;
3010 VALUE s = rb_check_string_type(arg);
3011 if (!NIL_P(s) && RSTRING_LEN(s) > 0) {
3012 arg = s;
3013 for (i=0; i<12; i++) {
3014 if (RSTRING_LEN(s) == 3 &&
3015 STRNCASECMP(months[i], RSTRING_PTR(s), 3) == 0) {
3016 mon = i+1;
3017 break;
3018 }
3019 }
3020 }
3021 if (mon == 0) {
3022 mon = obj2ubits(arg, 4);
3023 }
3024 return mon;
3025}
3026
3027static VALUE
3028validate_utc_offset(VALUE utc_offset)
3029{
3030 if (le(utc_offset, INT2FIX(-86400)) || ge(utc_offset, INT2FIX(86400)))
3031 rb_raise(rb_eArgError, "utc_offset out of range");
3032 return utc_offset;
3033}
3034
3035static VALUE
3036validate_zone_name(VALUE zone_name)
3037{
3038 StringValueCStr(zone_name);
3039 return zone_name;
3040}
3041
3042static void
3043validate_vtm(struct vtm *vtm)
3044{
3045#define validate_vtm_range(mem, b, e) \
3046 ((vtm->mem < b || vtm->mem > e) ? \
3047 rb_raise(rb_eArgError, #mem" out of range") : (void)0)
3048 validate_vtm_range(mon, 1, 12);
3049 validate_vtm_range(mday, 1, 31);
3050 validate_vtm_range(hour, 0, 24);
3051 validate_vtm_range(min, 0, (vtm->hour == 24 ? 0 : 59));
3052 validate_vtm_range(sec, 0, (vtm->hour == 24 ? 0 : 60));
3053 if (lt(vtm->subsecx, INT2FIX(0)) || ge(vtm->subsecx, INT2FIX(TIME_SCALE)))
3054 rb_raise(rb_eArgError, "subsecx out of range");
3055 if (!NIL_P(vtm->utc_offset)) validate_utc_offset(vtm->utc_offset);
3056#undef validate_vtm_range
3057}
3058
3059static void
3060time_arg(int argc, const VALUE *argv, struct vtm *vtm)
3061{
3062 VALUE v[8];
3063 VALUE subsecx = INT2FIX(0);
3064
3065 vtm->year = INT2FIX(0);
3066 vtm->mon = 0;
3067 vtm->mday = 0;
3068 vtm->hour = 0;
3069 vtm->min = 0;
3070 vtm->sec = 0;
3071 vtm->subsecx = INT2FIX(0);
3072 vtm->utc_offset = Qnil;
3073 vtm->wday = 0;
3074 vtm->yday = 0;
3075 vtm->isdst = 0;
3076 vtm->zone = str_empty;
3077
3078 if (argc == 10) {
3079 v[0] = argv[5];
3080 v[1] = argv[4];
3081 v[2] = argv[3];
3082 v[3] = argv[2];
3083 v[4] = argv[1];
3084 v[5] = argv[0];
3085 v[6] = Qnil;
3086 vtm->isdst = RTEST(argv[8]) ? 1 : 0;
3087 }
3088 else {
3089 rb_scan_args(argc, argv, "17", &v[0],&v[1],&v[2],&v[3],&v[4],&v[5],&v[6],&v[7]);
3090 /* v[6] may be usec or zone (parsedate) */
3091 /* v[7] is wday (parsedate; ignored) */
3092 vtm->wday = VTM_WDAY_INITVAL;
3093 vtm->isdst = VTM_ISDST_INITVAL;
3094 }
3095
3096 vtm->year = obj2vint(v[0]);
3097
3098 if (NIL_P(v[1])) {
3099 vtm->mon = 1;
3100 }
3101 else {
3102 vtm->mon = month_arg(v[1]);
3103 }
3104
3105 if (NIL_P(v[2])) {
3106 vtm->mday = 1;
3107 }
3108 else {
3109 vtm->mday = obj2ubits(v[2], 5);
3110 }
3111
3112 /* normalize month-mday */
3113 switch (vtm->mon) {
3114 case 2:
3115 {
3116 /* this drops higher bits but it's not a problem to calc leap year */
3117 unsigned int mday2 = leap_year_v_p(vtm->year) ? 29 : 28;
3118 if (vtm->mday > mday2) {
3119 vtm->mday -= mday2;
3120 vtm->mon++;
3121 }
3122 }
3123 break;
3124 case 4:
3125 case 6:
3126 case 9:
3127 case 11:
3128 if (vtm->mday == 31) {
3129 vtm->mon++;
3130 vtm->mday = 1;
3131 }
3132 break;
3133 }
3134
3135 vtm->hour = NIL_P(v[3])?0:obj2ubits(v[3], 5);
3136
3137 vtm->min = NIL_P(v[4])?0:obj2ubits(v[4], 6);
3138
3139 if (!NIL_P(v[6]) && argc == 7) {
3140 vtm->sec = NIL_P(v[5])?0:obj2ubits(v[5],6);
3141 subsecx = usec2subsecx(v[6]);
3142 }
3143 else {
3144 /* when argc == 8, v[6] is timezone, but ignored */
3145 if (NIL_P(v[5])) {
3146 vtm->sec = 0;
3147 }
3148 else {
3149 vtm->sec = obj2subsecx(v[5], &subsecx);
3150 }
3151 }
3152 vtm->subsecx = subsecx;
3153
3154 validate_vtm(vtm);
3155 RB_GC_GUARD(subsecx);
3156}
3157
3158static int
3159leap_year_p(long y)
3160{
3161 /* TODO:
3162 * ensure about negative years in proleptic Gregorian calendar.
3163 */
3164 unsigned long uy = (unsigned long)(LIKELY(y >= 0) ? y : -y);
3165
3166 if (LIKELY(uy % 4 != 0)) return 0;
3167
3168 unsigned long century = uy / 100;
3169 if (LIKELY(uy != century * 100)) return 1;
3170 return century % 4 == 0;
3171}
3172
3173static time_t
3174timegm_noleapsecond(struct tm *tm)
3175{
3176 long tm_year = tm->tm_year;
3177 int tm_yday = calc_tm_yday(tm->tm_year, tm->tm_mon, tm->tm_mday);
3178
3179 /*
3180 * `Seconds Since the Epoch' in SUSv3:
3181 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
3182 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
3183 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
3184 */
3185 return tm->tm_sec + tm->tm_min*60 + tm->tm_hour*3600 +
3186 (time_t)(tm_yday +
3187 (tm_year-70)*365 +
3188 DIV(tm_year-69,4) -
3189 DIV(tm_year-1,100) +
3190 DIV(tm_year+299,400))*86400;
3191}
3192
3193#if 0
3194#define DEBUG_FIND_TIME_NUMGUESS
3195#define DEBUG_GUESSRANGE
3196#endif
3197
3198static const bool debug_guessrange =
3199#ifdef DEBUG_GUESSRANGE
3200 true;
3201#else
3202 false;
3203#endif
3204
3205#define DEBUG_REPORT_GUESSRANGE \
3206 (debug_guessrange ? debug_report_guessrange(guess_lo, guess_hi) : (void)0)
3207
3208static inline void
3209debug_report_guessrange(time_t guess_lo, time_t guess_hi)
3210{
3211 time_t guess_diff = guess_hi - guess_lo;
3212 fprintf(stderr, "find time guess range: %"PRI_TIMET_PREFIX"d - "
3213 "%"PRI_TIMET_PREFIX"d : %"PRI_TIMET_PREFIX"u\n",
3214 guess_lo, guess_hi, guess_diff);
3215}
3216
3217static const bool debug_find_time_numguess =
3218#ifdef DEBUG_FIND_TIME_NUMGUESS
3219 true;
3220#else
3221 false;
3222#endif
3223
3224#define DEBUG_FIND_TIME_NUMGUESS_INC \
3225 (void)(debug_find_time_numguess && find_time_numguess++),
3226static unsigned long long find_time_numguess;
3227
3228static VALUE
3229find_time_numguess_getter(ID name, VALUE *data)
3230{
3231 unsigned long long *numguess = (void *)data;
3232 return ULL2NUM(*numguess);
3233}
3234
3235static const char *
3236find_time_t(struct tm *tptr, int utc_p, time_t *tp)
3237{
3238 time_t guess, guess0, guess_lo, guess_hi;
3239 struct tm *tm, tm0, tm_lo, tm_hi;
3240 int d;
3241 int find_dst;
3242 struct tm result;
3243 int status;
3244 int tptr_tm_yday;
3245
3246#define GUESS(p) (DEBUG_FIND_TIME_NUMGUESS_INC (utc_p ? gmtime_with_leapsecond((p), &result) : LOCALTIME((p), result)))
3247
3248 guess_lo = TIMET_MIN;
3249 guess_hi = TIMET_MAX;
3250
3251 find_dst = 0 < tptr->tm_isdst;
3252
3253 /* /etc/localtime might be changed. reload it. */
3254 update_tz();
3255
3256 tm0 = *tptr;
3257 if (tm0.tm_mon < 0) {
3258 tm0.tm_mon = 0;
3259 tm0.tm_mday = 1;
3260 tm0.tm_hour = 0;
3261 tm0.tm_min = 0;
3262 tm0.tm_sec = 0;
3263 }
3264 else if (11 < tm0.tm_mon) {
3265 tm0.tm_mon = 11;
3266 tm0.tm_mday = 31;
3267 tm0.tm_hour = 23;
3268 tm0.tm_min = 59;
3269 tm0.tm_sec = 60;
3270 }
3271 else if (tm0.tm_mday < 1) {
3272 tm0.tm_mday = 1;
3273 tm0.tm_hour = 0;
3274 tm0.tm_min = 0;
3275 tm0.tm_sec = 0;
3276 }
3277 else if ((d = days_in_month_in(1900 + tm0.tm_year)[tm0.tm_mon]) < tm0.tm_mday) {
3278 tm0.tm_mday = d;
3279 tm0.tm_hour = 23;
3280 tm0.tm_min = 59;
3281 tm0.tm_sec = 60;
3282 }
3283 else if (tm0.tm_hour < 0) {
3284 tm0.tm_hour = 0;
3285 tm0.tm_min = 0;
3286 tm0.tm_sec = 0;
3287 }
3288 else if (23 < tm0.tm_hour) {
3289 tm0.tm_hour = 23;
3290 tm0.tm_min = 59;
3291 tm0.tm_sec = 60;
3292 }
3293 else if (tm0.tm_min < 0) {
3294 tm0.tm_min = 0;
3295 tm0.tm_sec = 0;
3296 }
3297 else if (59 < tm0.tm_min) {
3298 tm0.tm_min = 59;
3299 tm0.tm_sec = 60;
3300 }
3301 else if (tm0.tm_sec < 0) {
3302 tm0.tm_sec = 0;
3303 }
3304 else if (60 < tm0.tm_sec) {
3305 tm0.tm_sec = 60;
3306 }
3307
3308 DEBUG_REPORT_GUESSRANGE;
3309 guess0 = guess = timegm_noleapsecond(&tm0);
3310 tm = GUESS(&guess);
3311 if (tm) {
3312 d = tmcmp(tptr, tm);
3313 if (d == 0) { goto found; }
3314 if (d < 0) {
3315 guess_hi = guess;
3316 guess -= 24 * 60 * 60;
3317 }
3318 else {
3319 guess_lo = guess;
3320 guess += 24 * 60 * 60;
3321 }
3322 DEBUG_REPORT_GUESSRANGE;
3323 if (guess_lo < guess && guess < guess_hi && (tm = GUESS(&guess)) != NULL) {
3324 d = tmcmp(tptr, tm);
3325 if (d == 0) { goto found; }
3326 if (d < 0)
3327 guess_hi = guess;
3328 else
3329 guess_lo = guess;
3330 DEBUG_REPORT_GUESSRANGE;
3331 }
3332 }
3333
3334 tm = GUESS(&guess_lo);
3335 if (!tm) goto error;
3336 d = tmcmp(tptr, tm);
3337 if (d < 0) goto out_of_range;
3338 if (d == 0) { guess = guess_lo; goto found; }
3339 tm_lo = *tm;
3340
3341 tm = GUESS(&guess_hi);
3342 if (!tm) goto error;
3343 d = tmcmp(tptr, tm);
3344 if (d > 0) goto out_of_range;
3345 if (d == 0) { guess = guess_hi; goto found; }
3346 tm_hi = *tm;
3347
3348 DEBUG_REPORT_GUESSRANGE;
3349
3350 status = 1;
3351
3352 while (guess_lo + 1 < guess_hi) {
3353 binsearch:
3354 if (status == 0) {
3355 guess = guess_lo / 2 + guess_hi / 2;
3356 if (guess <= guess_lo)
3357 guess = guess_lo + 1;
3358 else if (guess >= guess_hi)
3359 guess = guess_hi - 1;
3360 status = 1;
3361 }
3362 else {
3363 if (status == 1) {
3364 time_t guess0_hi = timegm_noleapsecond(&tm_hi);
3365 guess = guess_hi - (guess0_hi - guess0);
3366 if (guess == guess_hi) /* hh:mm:60 tends to cause this condition. */
3367 guess--;
3368 status = 2;
3369 }
3370 else if (status == 2) {
3371 time_t guess0_lo = timegm_noleapsecond(&tm_lo);
3372 guess = guess_lo + (guess0 - guess0_lo);
3373 if (guess == guess_lo)
3374 guess++;
3375 status = 0;
3376 }
3377 if (guess <= guess_lo || guess_hi <= guess) {
3378 /* Previous guess is invalid. try binary search. */
3379 if (debug_guessrange) {
3380 if (guess <= guess_lo) {
3381 fprintf(stderr, "too small guess: %"PRI_TIMET_PREFIX"d"\
3382 " <= %"PRI_TIMET_PREFIX"d\n", guess, guess_lo);
3383 }
3384 if (guess_hi <= guess) {
3385 fprintf(stderr, "too big guess: %"PRI_TIMET_PREFIX"d"\
3386 " <= %"PRI_TIMET_PREFIX"d\n", guess_hi, guess);
3387 }
3388 }
3389 status = 0;
3390 goto binsearch;
3391 }
3392 }
3393
3394 tm = GUESS(&guess);
3395 if (!tm) goto error;
3396
3397 d = tmcmp(tptr, tm);
3398
3399 if (d < 0) {
3400 guess_hi = guess;
3401 tm_hi = *tm;
3402 DEBUG_REPORT_GUESSRANGE;
3403 }
3404 else if (d > 0) {
3405 guess_lo = guess;
3406 tm_lo = *tm;
3407 DEBUG_REPORT_GUESSRANGE;
3408 }
3409 else {
3410 goto found;
3411 }
3412 }
3413
3414 /* Given argument has no corresponding time_t. Let's extrapolate. */
3415 /*
3416 * `Seconds Since the Epoch' in SUSv3:
3417 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
3418 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
3419 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
3420 */
3421
3422 tptr_tm_yday = calc_tm_yday(tptr->tm_year, tptr->tm_mon, tptr->tm_mday);
3423
3424 *tp = guess_lo +
3425 ((tptr->tm_year - tm_lo.tm_year) * 365 +
3426 DIV((tptr->tm_year-69), 4) -
3427 DIV((tptr->tm_year-1), 100) +
3428 DIV((tptr->tm_year+299), 400) -
3429 DIV((tm_lo.tm_year-69), 4) +
3430 DIV((tm_lo.tm_year-1), 100) -
3431 DIV((tm_lo.tm_year+299), 400) +
3432 tptr_tm_yday -
3433 tm_lo.tm_yday) * 86400 +
3434 (tptr->tm_hour - tm_lo.tm_hour) * 3600 +
3435 (tptr->tm_min - tm_lo.tm_min) * 60 +
3436 (tptr->tm_sec - (tm_lo.tm_sec == 60 ? 59 : tm_lo.tm_sec));
3437
3438 return NULL;
3439
3440 found:
3441 if (!utc_p) {
3442 /* If localtime is nonmonotonic, another result may exist. */
3443 time_t guess2;
3444 if (find_dst) {
3445 guess2 = guess - 2 * 60 * 60;
3446 tm = LOCALTIME(&guess2, result);
3447 if (tm) {
3448 if (tptr->tm_hour != (tm->tm_hour + 2) % 24 ||
3449 tptr->tm_min != tm->tm_min ||
3450 tptr->tm_sec != tm->tm_sec) {
3451 guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
3452 (tm->tm_min - tptr->tm_min) * 60 +
3453 (tm->tm_sec - tptr->tm_sec);
3454 if (tptr->tm_mday != tm->tm_mday)
3455 guess2 += 24 * 60 * 60;
3456 if (guess != guess2) {
3457 tm = LOCALTIME(&guess2, result);
3458 if (tm && tmcmp(tptr, tm) == 0) {
3459 if (guess < guess2)
3460 *tp = guess;
3461 else
3462 *tp = guess2;
3463 return NULL;
3464 }
3465 }
3466 }
3467 }
3468 }
3469 else {
3470 guess2 = guess + 2 * 60 * 60;
3471 tm = LOCALTIME(&guess2, result);
3472 if (tm) {
3473 if ((tptr->tm_hour + 2) % 24 != tm->tm_hour ||
3474 tptr->tm_min != tm->tm_min ||
3475 tptr->tm_sec != tm->tm_sec) {
3476 guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
3477 (tm->tm_min - tptr->tm_min) * 60 +
3478 (tm->tm_sec - tptr->tm_sec);
3479 if (tptr->tm_mday != tm->tm_mday)
3480 guess2 -= 24 * 60 * 60;
3481 if (guess != guess2) {
3482 tm = LOCALTIME(&guess2, result);
3483 if (tm && tmcmp(tptr, tm) == 0) {
3484 if (guess < guess2)
3485 *tp = guess2;
3486 else
3487 *tp = guess;
3488 return NULL;
3489 }
3490 }
3491 }
3492 }
3493 }
3494 }
3495 *tp = guess;
3496 return NULL;
3497
3498 out_of_range:
3499 return "time out of range";
3500
3501 error:
3502 return "gmtime/localtime error";
3503}
3504
3505static int
3506vtmcmp(struct vtm *a, struct vtm *b)
3507{
3508 if (ne(a->year, b->year))
3509 return lt(a->year, b->year) ? -1 : 1;
3510 else if (a->mon != b->mon)
3511 return a->mon < b->mon ? -1 : 1;
3512 else if (a->mday != b->mday)
3513 return a->mday < b->mday ? -1 : 1;
3514 else if (a->hour != b->hour)
3515 return a->hour < b->hour ? -1 : 1;
3516 else if (a->min != b->min)
3517 return a->min < b->min ? -1 : 1;
3518 else if (a->sec != b->sec)
3519 return a->sec < b->sec ? -1 : 1;
3520 else if (ne(a->subsecx, b->subsecx))
3521 return lt(a->subsecx, b->subsecx) ? -1 : 1;
3522 else
3523 return 0;
3524}
3525
3526static int
3527tmcmp(struct tm *a, struct tm *b)
3528{
3529 if (a->tm_year != b->tm_year)
3530 return a->tm_year < b->tm_year ? -1 : 1;
3531 else if (a->tm_mon != b->tm_mon)
3532 return a->tm_mon < b->tm_mon ? -1 : 1;
3533 else if (a->tm_mday != b->tm_mday)
3534 return a->tm_mday < b->tm_mday ? -1 : 1;
3535 else if (a->tm_hour != b->tm_hour)
3536 return a->tm_hour < b->tm_hour ? -1 : 1;
3537 else if (a->tm_min != b->tm_min)
3538 return a->tm_min < b->tm_min ? -1 : 1;
3539 else if (a->tm_sec != b->tm_sec)
3540 return a->tm_sec < b->tm_sec ? -1 : 1;
3541 else
3542 return 0;
3543}
3544
3545/*
3546 * call-seq:
3547 * Time.utc(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0) -> new_time
3548 * Time.utc(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy) -> new_time
3549 *
3550 * Returns a new \Time object based the on given arguments,
3551 * in the UTC timezone.
3552 *
3553 * With one to seven arguments given,
3554 * the arguments are interpreted as in the first calling sequence above:
3555 *
3556 * Time.utc(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0)
3557 *
3558 * Examples:
3559 *
3560 * Time.utc(2000) # => 2000-01-01 00:00:00 UTC
3561 * Time.utc(-2000) # => -2000-01-01 00:00:00 UTC
3562 *
3563 * There are no minimum and maximum values for the required argument +year+.
3564 *
3565 * For the optional arguments:
3566 *
3567 * - +month+: Month in range (1..12), or case-insensitive
3568 * 3-letter month name:
3569 *
3570 * Time.utc(2000, 1) # => 2000-01-01 00:00:00 UTC
3571 * Time.utc(2000, 12) # => 2000-12-01 00:00:00 UTC
3572 * Time.utc(2000, 'jan') # => 2000-01-01 00:00:00 UTC
3573 * Time.utc(2000, 'JAN') # => 2000-01-01 00:00:00 UTC
3574 *
3575 * - +mday+: Month day in range(1..31):
3576 *
3577 * Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC
3578 * Time.utc(2000, 1, 31) # => 2000-01-31 00:00:00 UTC
3579 *
3580 * - +hour+: Hour in range (0..23), or 24 if +min+, +sec+, and +usec+
3581 * are zero:
3582 *
3583 * Time.utc(2000, 1, 1, 0) # => 2000-01-01 00:00:00 UTC
3584 * Time.utc(2000, 1, 1, 23) # => 2000-01-01 23:00:00 UTC
3585 * Time.utc(2000, 1, 1, 24) # => 2000-01-02 00:00:00 UTC
3586 *
3587 * - +min+: Minute in range (0..59):
3588 *
3589 * Time.utc(2000, 1, 1, 0, 0) # => 2000-01-01 00:00:00 UTC
3590 * Time.utc(2000, 1, 1, 0, 59) # => 2000-01-01 00:59:00 UTC
3591 *
3592 * - +sec+: Second in range (0..59), or 60 if +usec+ is zero:
3593 *
3594 * Time.utc(2000, 1, 1, 0, 0, 0) # => 2000-01-01 00:00:00 UTC
3595 * Time.utc(2000, 1, 1, 0, 0, 59) # => 2000-01-01 00:00:59 UTC
3596 * Time.utc(2000, 1, 1, 0, 0, 60) # => 2000-01-01 00:01:00 UTC
3597 *
3598 * - +usec+: Microsecond in range (0..999999):
3599 *
3600 * Time.utc(2000, 1, 1, 0, 0, 0, 0) # => 2000-01-01 00:00:00 UTC
3601 * Time.utc(2000, 1, 1, 0, 0, 0, 999999) # => 2000-01-01 00:00:00.999999 UTC
3602 *
3603 * The values may be:
3604 *
3605 * - Integers, as above.
3606 * - Numerics convertible to integers:
3607 *
3608 * Time.utc(Float(0.0), Rational(1, 1), 1.0, 0.0, 0.0, 0.0, 0.0)
3609 * # => 0000-01-01 00:00:00 UTC
3610 *
3611 * - \String integers:
3612 *
3613 * a = %w[0 1 1 0 0 0 0 0]
3614 * # => ["0", "1", "1", "0", "0", "0", "0", "0"]
3615 * Time.utc(*a) # => 0000-01-01 00:00:00 UTC
3616 *
3617 * When exactly ten arguments are given,
3618 * the arguments are interpreted as in the second calling sequence above:
3619 *
3620 * Time.utc(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy)
3621 *
3622 * where the +dummy+ arguments are ignored:
3623 *
3624 * a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3625 * # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3626 * Time.utc(*a) # => 0005-04-03 02:01:00 UTC
3627 *
3628 * This form is useful for creating a \Time object from a 10-element
3629 * array returned by Time.to_a:
3630 *
3631 * t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006
3632 * a = t.to_a # => [5, 4, 3, 2, 1, 2000, 0, 2, false, nil]
3633 * Time.utc(*a) # => 2000-01-02 03:04:05 UTC
3634 *
3635 * The two forms have their first six arguments in common,
3636 * though in different orders;
3637 * the ranges of these common arguments are the same for both forms; see above.
3638 *
3639 * Raises an exception if the number of arguments is eight, nine,
3640 * or greater than ten.
3641 *
3642 * Time.gm is an alias for Time.utc.
3643 *
3644 * Related: Time.local.
3645 *
3646 */
3647static VALUE
3648time_s_mkutc(int argc, VALUE *argv, VALUE klass)
3649{
3650 struct vtm vtm;
3651
3652 time_arg(argc, argv, &vtm);
3653 return time_gmtime(time_new_timew(klass, timegmw(&vtm)));
3654}
3655
3656/*
3657 * call-seq:
3658 * Time.local(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0) -> new_time
3659 * Time.local(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy) -> new_time
3660 *
3661 * Like Time.utc, except that the returned \Time object
3662 * has the local timezone, not the UTC timezone:
3663 *
3664 * # With seven arguments.
3665 * Time.local(0, 1, 2, 3, 4, 5, 6)
3666 * # => 0000-01-02 03:04:05.000006 -0600
3667 * # With exactly ten arguments.
3668 * Time.local(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
3669 * # => 0005-04-03 02:01:00 -0600
3670 *
3671 */
3672
3673static VALUE
3674time_s_mktime(int argc, VALUE *argv, VALUE klass)
3675{
3676 struct vtm vtm;
3677
3678 time_arg(argc, argv, &vtm);
3679 return time_localtime(time_new_timew(klass, timelocalw(&vtm)));
3680}
3681
3682/*
3683 * call-seq:
3684 * to_i -> integer
3685 *
3686 * Returns the value of +self+ as integer
3687 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3688 * subseconds are truncated (not rounded):
3689 *
3690 * Time.utc(1970, 1, 1, 0, 0, 0).to_i # => 0
3691 * Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_i # => 0
3692 * Time.utc(1950, 1, 1, 0, 0, 0).to_i # => -631152000
3693 * Time.utc(1990, 1, 1, 0, 0, 0).to_i # => 631152000
3694 *
3695 * Time#tv_sec is an alias for Time#to_i.
3696 *
3697 * Related: Time#to_f Time#to_r.
3698 */
3699
3700static VALUE
3701time_to_i(VALUE time)
3702{
3703 struct time_object *tobj;
3704
3705 GetTimeval(time, tobj);
3706 return w2v(wdiv(tobj->timew, WINT2FIXWV(TIME_SCALE)));
3707}
3708
3709/*
3710 * call-seq:
3711 * to_f -> float
3712 *
3713 * Returns the value of +self+ as a Float number
3714 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3715 * subseconds are included.
3716 *
3717 * The stored value of +self+ is a
3718 * {Rational}[rdoc-ref:Rational@#method-i-to_f],
3719 * which means that the returned value may be approximate:
3720 *
3721 * Time.utc(1970, 1, 1, 0, 0, 0).to_f # => 0.0
3722 * Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_f # => 0.999999
3723 * Time.utc(1950, 1, 1, 0, 0, 0).to_f # => -631152000.0
3724 * Time.utc(1990, 1, 1, 0, 0, 0).to_f # => 631152000.0
3725 *
3726 * Related: Time#to_i, Time#to_r.
3727 */
3728
3729static VALUE
3730time_to_f(VALUE time)
3731{
3732 struct time_object *tobj;
3733
3734 GetTimeval(time, tobj);
3735 return rb_Float(rb_time_unmagnify_to_float(tobj->timew));
3736}
3737
3738/*
3739 * call-seq:
3740 * to_r -> rational
3741 *
3742 * Returns the value of +self+ as a Rational exact number of
3743 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3744 *
3745 * Time.now.to_r # => (16571402750320203/10000000)
3746 *
3747 * Related: Time#to_f, Time#to_i.
3748 */
3749
3750static VALUE
3751time_to_r(VALUE time)
3752{
3753 struct time_object *tobj;
3754 VALUE v;
3755
3756 GetTimeval(time, tobj);
3757 v = rb_time_unmagnify_to_rational(tobj->timew);
3758 if (!RB_TYPE_P(v, T_RATIONAL)) {
3759 v = rb_Rational1(v);
3760 }
3761 return v;
3762}
3763
3764/*
3765 * call-seq:
3766 * usec -> integer
3767 *
3768 * Returns the number of microseconds in the subseconds part of +self+
3769 * in the range (0..999_999);
3770 * lower-order digits are truncated, not rounded:
3771 *
3772 * t = Time.now # => 2022-07-11 14:59:47.5484697 -0500
3773 * t.usec # => 548469
3774 *
3775 * Related: Time#subsec (returns exact subseconds).
3776 *
3777 * Time#tv_usec is an alias for Time#usec.
3778 */
3779
3780static VALUE
3781time_usec(VALUE time)
3782{
3783 struct time_object *tobj;
3784 wideval_t w, q, r;
3785
3786 GetTimeval(time, tobj);
3787
3788 w = wmod(tobj->timew, WINT2WV(TIME_SCALE));
3789 wmuldivmod(w, WINT2FIXWV(1000000), WINT2FIXWV(TIME_SCALE), &q, &r);
3790 return rb_to_int(w2v(q));
3791}
3792
3793/*
3794 * call-seq:
3795 * nsec -> integer
3796 *
3797 * Returns the number of nanoseconds in the subseconds part of +self+
3798 * in the range (0..999_999_999);
3799 * lower-order digits are truncated, not rounded:
3800 *
3801 * t = Time.now # => 2022-07-11 15:04:53.3219637 -0500
3802 * t.nsec # => 321963700
3803 *
3804 * Related: Time#subsec (returns exact subseconds).
3805 *
3806 * Time#tv_nsec is an alias for Time#usec.
3807 */
3808
3809static VALUE
3810time_nsec(VALUE time)
3811{
3812 struct time_object *tobj;
3813
3814 GetTimeval(time, tobj);
3815 return rb_to_int(w2v(wmulquoll(wmod(tobj->timew, WINT2WV(TIME_SCALE)), 1000000000, TIME_SCALE)));
3816}
3817
3818/*
3819 * call-seq:
3820 * subsec -> numeric
3821 *
3822 * Returns the exact subseconds for +self+ as a Numeric
3823 * (Integer or Rational):
3824 *
3825 * t = Time.now # => 2022-07-11 15:11:36.8490302 -0500
3826 * t.subsec # => (4245151/5000000)
3827 *
3828 * If the subseconds is zero, returns integer zero:
3829 *
3830 * t = Time.new(2000, 1, 1, 2, 3, 4) # => 2000-01-01 02:03:04 -0600
3831 * t.subsec # => 0
3832 *
3833 */
3834
3835static VALUE
3836time_subsec(VALUE time)
3837{
3838 struct time_object *tobj;
3839
3840 GetTimeval(time, tobj);
3841 return quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE));
3842}
3843
3844/*
3845 * call-seq:
3846 * self <=> other_time -> -1, 0, +1, or nil
3847 *
3848 * Compares +self+ with +other_time+; returns:
3849 *
3850 * - +-1+, if +self+ is less than +other_time+.
3851 * - +0+, if +self+ is equal to +other_time+.
3852 * - +1+, if +self+ is greater then +other_time+.
3853 * - +nil+, if +self+ and +other_time+ are incomparable.
3854 *
3855 * Examples:
3856 *
3857 * t = Time.now # => 2007-11-19 08:12:12 -0600
3858 * t2 = t + 2592000 # => 2007-12-19 08:12:12 -0600
3859 * t <=> t2 # => -1
3860 * t2 <=> t # => 1
3861 *
3862 * t = Time.now # => 2007-11-19 08:13:38 -0600
3863 * t2 = t + 0.1 # => 2007-11-19 08:13:38 -0600
3864 * t.nsec # => 98222999
3865 * t2.nsec # => 198222999
3866 * t <=> t2 # => -1
3867 * t2 <=> t # => 1
3868 * t <=> t # => 0
3869 *
3870 */
3871
3872static VALUE
3873time_cmp(VALUE time1, VALUE time2)
3874{
3875 struct time_object *tobj1, *tobj2;
3876 int n;
3877
3878 GetTimeval(time1, tobj1);
3879 if (IsTimeval(time2)) {
3880 GetTimeval(time2, tobj2);
3881 n = wcmp(tobj1->timew, tobj2->timew);
3882 }
3883 else {
3884 return rb_invcmp(time1, time2);
3885 }
3886 if (n == 0) return INT2FIX(0);
3887 if (n > 0) return INT2FIX(1);
3888 return INT2FIX(-1);
3889}
3890
3891/*
3892 * call-seq:
3893 * eql?(other_time)
3894 *
3895 * Returns +true+ if +self+ and +other_time+ are
3896 * both \Time objects with the exact same time value.
3897 */
3898
3899static VALUE
3900time_eql(VALUE time1, VALUE time2)
3901{
3902 struct time_object *tobj1, *tobj2;
3903
3904 GetTimeval(time1, tobj1);
3905 if (IsTimeval(time2)) {
3906 GetTimeval(time2, tobj2);
3907 return rb_equal(w2v(tobj1->timew), w2v(tobj2->timew));
3908 }
3909 return Qfalse;
3910}
3911
3912/*
3913 * call-seq:
3914 * utc? -> true or false
3915 *
3916 * Returns +true+ if +self+ represents a time in UTC (GMT):
3917 *
3918 * now = Time.now
3919 * # => 2022-08-18 10:24:13.5398485 -0500
3920 * now.utc? # => false
3921 * utc = Time.utc(2000, 1, 1, 20, 15, 1)
3922 * # => 2000-01-01 20:15:01 UTC
3923 * utc.utc? # => true
3924 *
3925 * Time#gmt? is an alias for Time#utc?.
3926 *
3927 * Related: Time.utc.
3928 */
3929
3930static VALUE
3931time_utc_p(VALUE time)
3932{
3933 struct time_object *tobj;
3934
3935 GetTimeval(time, tobj);
3936 return RBOOL(TZMODE_UTC_P(tobj));
3937}
3938
3939/*
3940 * call-seq:
3941 * hash -> integer
3942 *
3943 * Returns the integer hash code for +self+.
3944 *
3945 * Related: Object#hash.
3946 */
3947
3948static VALUE
3949time_hash(VALUE time)
3950{
3951 struct time_object *tobj;
3952
3953 GetTimeval(time, tobj);
3954 return rb_hash(w2v(tobj->timew));
3955}
3956
3957/* :nodoc: */
3958static VALUE
3959time_init_copy(VALUE copy, VALUE time)
3960{
3961 struct time_object *tobj, *tcopy;
3962
3963 if (!OBJ_INIT_COPY(copy, time)) return copy;
3964 GetTimeval(time, tobj);
3965 GetNewTimeval(copy, tcopy);
3966 MEMCPY(tcopy, tobj, struct time_object, 1);
3967
3968 return copy;
3969}
3970
3971static VALUE
3972time_dup(VALUE time)
3973{
3974 VALUE dup = time_s_alloc(rb_obj_class(time));
3975 time_init_copy(dup, time);
3976 return dup;
3977}
3978
3979static VALUE
3980time_localtime(VALUE time)
3981{
3982 struct time_object *tobj;
3983 struct vtm vtm;
3984 VALUE zone;
3985
3986 GetTimeval(time, tobj);
3987 if (TZMODE_LOCALTIME_P(tobj)) {
3988 if (tobj->tm_got)
3989 return time;
3990 }
3991 else {
3992 time_modify(time);
3993 }
3994
3995 zone = tobj->vtm.zone;
3996 if (maybe_tzobj_p(zone) && zone_localtime(zone, time)) {
3997 return time;
3998 }
3999
4000 if (!localtimew(tobj->timew, &vtm))
4001 rb_raise(rb_eArgError, "localtime error");
4002 tobj->vtm = vtm;
4003
4004 tobj->tm_got = 1;
4005 TZMODE_SET_LOCALTIME(tobj);
4006 return time;
4007}
4008
4009static VALUE
4010time_zonelocal(VALUE time, VALUE off)
4011{
4012 VALUE zone = off;
4013 if (zone_localtime(zone, time)) return time;
4014
4015 if (NIL_P(off = utc_offset_arg(off))) {
4016 off = zone;
4017 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
4018 if (!zone_localtime(zone, time)) invalid_utc_offset(off);
4019 return time;
4020 }
4021 else if (off == UTC_ZONE) {
4022 return time_gmtime(time);
4023 }
4024 validate_utc_offset(off);
4025
4026 time_set_utc_offset(time, off);
4027 return time_fixoff(time);
4028}
4029
4030/*
4031 * call-seq:
4032 * localtime -> self or new_time
4033 * localtime(zone) -> new_time
4034 *
4035 * With no argument given:
4036 *
4037 * - Returns +self+ if +self+ is a local time.
4038 * - Otherwise returns a new \Time in the user's local timezone:
4039 *
4040 * t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC
4041 * t.localtime # => 2000-01-01 14:15:01 -0600
4042 *
4043 * With argument +zone+ given,
4044 * returns the new \Time object created by converting
4045 * +self+ to the given time zone:
4046 *
4047 * t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC
4048 * t.localtime("-09:00") # => 2000-01-01 11:15:01 -0900
4049 *
4050 * For forms of argument +zone+, see
4051 * {Timezone Specifiers}[rdoc-ref:timezones.rdoc].
4052 *
4053 */
4054
4055static VALUE
4056time_localtime_m(int argc, VALUE *argv, VALUE time)
4057{
4058 VALUE off;
4059
4060 if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
4061 return time_zonelocal(time, off);
4062 }
4063
4064 return time_localtime(time);
4065}
4066
4067/*
4068 * call-seq:
4069 * utc -> self
4070 *
4071 * Returns +self+, converted to the UTC timezone:
4072 *
4073 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4074 * t.utc? # => false
4075 * t.utc # => 2000-01-01 06:00:00 UTC
4076 * t.utc? # => true
4077 *
4078 * Time#gmtime is an alias for Time#utc.
4079 *
4080 * Related: Time#getutc (returns a new converted \Time object).
4081 */
4082
4083static VALUE
4084time_gmtime(VALUE time)
4085{
4086 struct time_object *tobj;
4087 struct vtm vtm;
4088
4089 GetTimeval(time, tobj);
4090 if (TZMODE_UTC_P(tobj)) {
4091 if (tobj->tm_got)
4092 return time;
4093 }
4094 else {
4095 time_modify(time);
4096 }
4097
4098 vtm.zone = str_utc;
4099 GMTIMEW(tobj->timew, &vtm);
4100 tobj->vtm = vtm;
4101
4102 tobj->tm_got = 1;
4103 TZMODE_SET_UTC(tobj);
4104 return time;
4105}
4106
4107static VALUE
4108time_fixoff(VALUE time)
4109{
4110 struct time_object *tobj;
4111 struct vtm vtm;
4112 VALUE off, zone;
4113
4114 GetTimeval(time, tobj);
4115 if (TZMODE_FIXOFF_P(tobj)) {
4116 if (tobj->tm_got)
4117 return time;
4118 }
4119 else {
4120 time_modify(time);
4121 }
4122
4123 if (TZMODE_FIXOFF_P(tobj))
4124 off = tobj->vtm.utc_offset;
4125 else
4126 off = INT2FIX(0);
4127
4128 GMTIMEW(tobj->timew, &vtm);
4129
4130 zone = tobj->vtm.zone;
4131 tobj->vtm = vtm;
4132 tobj->vtm.zone = zone;
4133 vtm_add_offset(&tobj->vtm, off, +1);
4134
4135 tobj->tm_got = 1;
4136 TZMODE_SET_FIXOFF(tobj, off);
4137 return time;
4138}
4139
4140/*
4141 * call-seq:
4142 * getlocal(zone = nil) -> new_time
4143 *
4144 * Returns a new \Time object representing the value of +self+
4145 * converted to a given timezone;
4146 * if +zone+ is +nil+, the local timezone is used:
4147 *
4148 * t = Time.utc(2000) # => 2000-01-01 00:00:00 UTC
4149 * t.getlocal # => 1999-12-31 18:00:00 -0600
4150 * t.getlocal('+12:00') # => 2000-01-01 12:00:00 +1200
4151 *
4152 * For forms of argument +zone+, see
4153 * {Timezone Specifiers}[rdoc-ref:timezones.rdoc].
4154 *
4155 */
4156
4157static VALUE
4158time_getlocaltime(int argc, VALUE *argv, VALUE time)
4159{
4160 VALUE off;
4161
4162 if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
4163 VALUE zone = off;
4164 if (maybe_tzobj_p(zone)) {
4165 VALUE t = time_dup(time);
4166 if (zone_localtime(off, t)) return t;
4167 }
4168
4169 if (NIL_P(off = utc_offset_arg(off))) {
4170 off = zone;
4171 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
4172 time = time_dup(time);
4173 if (!zone_localtime(zone, time)) invalid_utc_offset(off);
4174 return time;
4175 }
4176 else if (off == UTC_ZONE) {
4177 return time_gmtime(time_dup(time));
4178 }
4179 validate_utc_offset(off);
4180
4181 time = time_dup(time);
4182 time_set_utc_offset(time, off);
4183 return time_fixoff(time);
4184 }
4185
4186 return time_localtime(time_dup(time));
4187}
4188
4189/*
4190 * call-seq:
4191 * getutc -> new_time
4192 *
4193 * Returns a new \Time object representing the value of +self+
4194 * converted to the UTC timezone:
4195 *
4196 * local = Time.local(2000) # => 2000-01-01 00:00:00 -0600
4197 * local.utc? # => false
4198 * utc = local.getutc # => 2000-01-01 06:00:00 UTC
4199 * utc.utc? # => true
4200 * utc == local # => true
4201 *
4202 * Time#getgm is an alias for Time#getutc.
4203 */
4204
4205static VALUE
4206time_getgmtime(VALUE time)
4207{
4208 return time_gmtime(time_dup(time));
4209}
4210
4211static VALUE
4212time_get_tm(VALUE time, struct time_object *tobj)
4213{
4214 if (TZMODE_UTC_P(tobj)) return time_gmtime(time);
4215 if (TZMODE_FIXOFF_P(tobj)) return time_fixoff(time);
4216 return time_localtime(time);
4217}
4218
4219static VALUE strftime_cstr(const char *fmt, size_t len, VALUE time, rb_encoding *enc);
4220#define strftimev(fmt, time, enc) strftime_cstr((fmt), rb_strlen_lit(fmt), (time), (enc))
4221
4222/*
4223 * call-seq:
4224 * ctime -> string
4225 *
4226 * Returns a string representation of +self+,
4227 * formatted by <tt>strftime('%a %b %e %T %Y')</tt>
4228 * or its shorthand version <tt>strftime('%c')</tt>;
4229 * see {Formats for Dates and Times}[rdoc-ref:strftime_formatting.rdoc]:
4230 *
4231 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4232 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4233 * t.strftime('%a %b %e %T %Y') # => "Sun Dec 31 23:59:59 2000"
4234 * t.strftime('%c') # => "Sun Dec 31 23:59:59 2000"
4235 *
4236 * Time#asctime is an alias for Time#ctime.
4237 *
4238 * Related: Time#to_s, Time#inspect:
4239 *
4240 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4241 * t.to_s # => "2000-12-31 23:59:59 +0000"
4242 *
4243 */
4244
4245static VALUE
4246time_asctime(VALUE time)
4247{
4248 return strftimev("%a %b %e %T %Y", time, rb_usascii_encoding());
4249}
4250
4251/*
4252 * call-seq:
4253 * to_s -> string
4254 *
4255 * Returns a string representation of +self+, without subseconds:
4256 *
4257 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4258 * t.to_s # => "2000-12-31 23:59:59 +0000"
4259 *
4260 * Related: Time#ctime, Time#inspect:
4261 *
4262 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4263 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4264 *
4265 */
4266
4267static VALUE
4268time_to_s(VALUE time)
4269{
4270 struct time_object *tobj;
4271
4272 GetTimeval(time, tobj);
4273 if (TZMODE_UTC_P(tobj))
4274 return strftimev("%Y-%m-%d %H:%M:%S UTC", time, rb_usascii_encoding());
4275 else
4276 return strftimev("%Y-%m-%d %H:%M:%S %z", time, rb_usascii_encoding());
4277}
4278
4279/*
4280 * call-seq:
4281 * inspect -> string
4282 *
4283 * Returns a string representation of +self+ with subseconds:
4284 *
4285 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4286 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4287 *
4288 * Related: Time#ctime, Time#to_s:
4289 *
4290 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4291 * t.to_s # => "2000-12-31 23:59:59 +0000"
4292 *
4293 */
4294
4295static VALUE
4296time_inspect(VALUE time)
4297{
4298 struct time_object *tobj;
4299 VALUE str, subsec;
4300
4301 GetTimeval(time, tobj);
4302 str = strftimev("%Y-%m-%d %H:%M:%S", time, rb_usascii_encoding());
4303 subsec = w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE)));
4304 if (subsec == INT2FIX(0)) {
4305 }
4306 else if (FIXNUM_P(subsec) && FIX2LONG(subsec) < TIME_SCALE) {
4307 long len;
4308 rb_str_catf(str, ".%09ld", FIX2LONG(subsec));
4309 for (len=RSTRING_LEN(str); RSTRING_PTR(str)[len-1] == '0' && len > 0; len--)
4310 ;
4311 rb_str_resize(str, len);
4312 }
4313 else {
4314 rb_str_cat_cstr(str, " ");
4315 subsec = quov(subsec, INT2FIX(TIME_SCALE));
4316 rb_str_concat(str, rb_obj_as_string(subsec));
4317 }
4318 if (TZMODE_UTC_P(tobj)) {
4319 rb_str_cat_cstr(str, " UTC");
4320 }
4321 else {
4322 /* ?TODO: subsecond offset */
4323 long off = NUM2LONG(rb_funcall(tobj->vtm.utc_offset, rb_intern("round"), 0));
4324 char sign = (off < 0) ? (off = -off, '-') : '+';
4325 int sec = off % 60;
4326 int min = (off /= 60) % 60;
4327 off /= 60;
4328 rb_str_catf(str, " %c%.2d%.2d", sign, (int)off, min);
4329 if (sec) rb_str_catf(str, "%.2d", sec);
4330 }
4331 return str;
4332}
4333
4334static VALUE
4335time_add0(VALUE klass, const struct time_object *tobj, VALUE torig, VALUE offset, int sign)
4336{
4337 VALUE result;
4338 struct time_object *result_tobj;
4339
4340 offset = num_exact(offset);
4341 if (sign < 0)
4342 result = time_new_timew(klass, wsub(tobj->timew, rb_time_magnify(v2w(offset))));
4343 else
4344 result = time_new_timew(klass, wadd(tobj->timew, rb_time_magnify(v2w(offset))));
4345 GetTimeval(result, result_tobj);
4346 TZMODE_COPY(result_tobj, tobj);
4347
4348 return result;
4349}
4350
4351static VALUE
4352time_add(const struct time_object *tobj, VALUE torig, VALUE offset, int sign)
4353{
4354 return time_add0(rb_cTime, tobj, torig, offset, sign);
4355}
4356
4357/*
4358 * call-seq:
4359 * self + numeric -> new_time
4360 *
4361 * Returns a new \Time object whose value is the sum of the numeric value
4362 * of +self+ and the given +numeric+:
4363 *
4364 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4365 * t + (60 * 60 * 24) # => 2000-01-02 00:00:00 -0600
4366 * t + 0.5 # => 2000-01-01 00:00:00.5 -0600
4367 *
4368 * Related: Time#-.
4369 */
4370
4371static VALUE
4372time_plus(VALUE time1, VALUE time2)
4373{
4374 struct time_object *tobj;
4375 GetTimeval(time1, tobj);
4376
4377 if (IsTimeval(time2)) {
4378 rb_raise(rb_eTypeError, "time + time?");
4379 }
4380 return time_add(tobj, time1, time2, 1);
4381}
4382
4383/*
4384 * call-seq:
4385 * self - numeric -> new_time
4386 * self - other_time -> float
4387 *
4388 * When +numeric+ is given,
4389 * returns a new \Time object whose value is the difference
4390 * of the numeric value of +self+ and +numeric+:
4391 *
4392 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4393 * t - (60 * 60 * 24) # => 1999-12-31 00:00:00 -0600
4394 * t - 0.5 # => 1999-12-31 23:59:59.5 -0600
4395 *
4396 * When +other_time+ is given,
4397 * returns a Float whose value is the difference
4398 * of the numeric values of +self+ and +other_time+:
4399 *
4400 * t - t # => 0.0
4401 *
4402 * Related: Time#+.
4403 */
4404
4405static VALUE
4406time_minus(VALUE time1, VALUE time2)
4407{
4408 struct time_object *tobj;
4409
4410 GetTimeval(time1, tobj);
4411 if (IsTimeval(time2)) {
4412 struct time_object *tobj2;
4413
4414 GetTimeval(time2, tobj2);
4415 return rb_Float(rb_time_unmagnify_to_float(wsub(tobj->timew, tobj2->timew)));
4416 }
4417 return time_add(tobj, time1, time2, -1);
4418}
4419
4420static VALUE
4421ndigits_denominator(VALUE ndigits)
4422{
4423 long nd = NUM2LONG(ndigits);
4424
4425 if (nd < 0) {
4426 rb_raise(rb_eArgError, "negative ndigits given");
4427 }
4428 if (nd == 0) {
4429 return INT2FIX(1);
4430 }
4431 return rb_rational_new(INT2FIX(1),
4432 rb_int_positive_pow(10, (unsigned long)nd));
4433}
4434
4435/*
4436 * call-seq:
4437 * round(ndigits = 0) -> new_time
4438 *
4439 * Returns a new \Time object whose numeric value is that of +self+,
4440 * with its seconds value rounded to precision +ndigits+:
4441 *
4442 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4443 * t # => 2010-03-30 05:43:25.123456789 UTC
4444 * t.round # => 2010-03-30 05:43:25 UTC
4445 * t.round(0) # => 2010-03-30 05:43:25 UTC
4446 * t.round(1) # => 2010-03-30 05:43:25.1 UTC
4447 * t.round(2) # => 2010-03-30 05:43:25.12 UTC
4448 * t.round(3) # => 2010-03-30 05:43:25.123 UTC
4449 * t.round(4) # => 2010-03-30 05:43:25.1235 UTC
4450 *
4451 * t = Time.utc(1999, 12,31, 23, 59, 59)
4452 * t # => 1999-12-31 23:59:59 UTC
4453 * (t + 0.4).round # => 1999-12-31 23:59:59 UTC
4454 * (t + 0.49).round # => 1999-12-31 23:59:59 UTC
4455 * (t + 0.5).round # => 2000-01-01 00:00:00 UTC
4456 * (t + 1.4).round # => 2000-01-01 00:00:00 UTC
4457 * (t + 1.49).round # => 2000-01-01 00:00:00 UTC
4458 * (t + 1.5).round # => 2000-01-01 00:00:01 UTC
4459 *
4460 * Related: Time#ceil, Time#floor.
4461 */
4462
4463static VALUE
4464time_round(int argc, VALUE *argv, VALUE time)
4465{
4466 VALUE ndigits, v, den;
4467 struct time_object *tobj;
4468
4469 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4470 den = INT2FIX(1);
4471 else
4472 den = ndigits_denominator(ndigits);
4473
4474 GetTimeval(time, tobj);
4475 v = w2v(rb_time_unmagnify(tobj->timew));
4476
4477 v = modv(v, den);
4478 if (lt(v, quov(den, INT2FIX(2))))
4479 return time_add(tobj, time, v, -1);
4480 else
4481 return time_add(tobj, time, subv(den, v), 1);
4482}
4483
4484/*
4485 * call-seq:
4486 * floor(ndigits = 0) -> new_time
4487 *
4488 * Returns a new \Time object whose numerical value
4489 * is less than or equal to +self+ with its seconds
4490 * truncated to precision +ndigits+:
4491 *
4492 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4493 * t # => 2010-03-30 05:43:25.123456789 UTC
4494 * t.floor # => 2010-03-30 05:43:25 UTC
4495 * t.floor(2) # => 2010-03-30 05:43:25.12 UTC
4496 * t.floor(4) # => 2010-03-30 05:43:25.1234 UTC
4497 * t.floor(6) # => 2010-03-30 05:43:25.123456 UTC
4498 * t.floor(8) # => 2010-03-30 05:43:25.12345678 UTC
4499 * t.floor(10) # => 2010-03-30 05:43:25.123456789 UTC
4500 *
4501 * t = Time.utc(1999, 12, 31, 23, 59, 59)
4502 * t # => 1999-12-31 23:59:59 UTC
4503 * (t + 0.4).floor # => 1999-12-31 23:59:59 UTC
4504 * (t + 0.9).floor # => 1999-12-31 23:59:59 UTC
4505 * (t + 1.4).floor # => 2000-01-01 00:00:00 UTC
4506 * (t + 1.9).floor # => 2000-01-01 00:00:00 UTC
4507 *
4508 * Related: Time#ceil, Time#round.
4509 */
4510
4511static VALUE
4512time_floor(int argc, VALUE *argv, VALUE time)
4513{
4514 VALUE ndigits, v, den;
4515 struct time_object *tobj;
4516
4517 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4518 den = INT2FIX(1);
4519 else
4520 den = ndigits_denominator(ndigits);
4521
4522 GetTimeval(time, tobj);
4523 v = w2v(rb_time_unmagnify(tobj->timew));
4524
4525 v = modv(v, den);
4526 return time_add(tobj, time, v, -1);
4527}
4528
4529/*
4530 * call-seq:
4531 * ceil(ndigits = 0) -> new_time
4532 *
4533 * Returns a new \Time object whose numerical value
4534 * is greater than or equal to +self+ with its seconds
4535 * truncated to precision +ndigits+:
4536 *
4537 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4538 * t # => 2010-03-30 05:43:25.123456789 UTC
4539 * t.ceil # => 2010-03-30 05:43:26 UTC
4540 * t.ceil(2) # => 2010-03-30 05:43:25.13 UTC
4541 * t.ceil(4) # => 2010-03-30 05:43:25.1235 UTC
4542 * t.ceil(6) # => 2010-03-30 05:43:25.123457 UTC
4543 * t.ceil(8) # => 2010-03-30 05:43:25.12345679 UTC
4544 * t.ceil(10) # => 2010-03-30 05:43:25.123456789 UTC
4545 *
4546 * t = Time.utc(1999, 12, 31, 23, 59, 59)
4547 * t # => 1999-12-31 23:59:59 UTC
4548 * (t + 0.4).ceil # => 2000-01-01 00:00:00 UTC
4549 * (t + 0.9).ceil # => 2000-01-01 00:00:00 UTC
4550 * (t + 1.4).ceil # => 2000-01-01 00:00:01 UTC
4551 * (t + 1.9).ceil # => 2000-01-01 00:00:01 UTC
4552 *
4553 * Related: Time#floor, Time#round.
4554 */
4555
4556static VALUE
4557time_ceil(int argc, VALUE *argv, VALUE time)
4558{
4559 VALUE ndigits, v, den;
4560 struct time_object *tobj;
4561
4562 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4563 den = INT2FIX(1);
4564 else
4565 den = ndigits_denominator(ndigits);
4566
4567 GetTimeval(time, tobj);
4568 v = w2v(rb_time_unmagnify(tobj->timew));
4569
4570 v = modv(v, den);
4571 if (!rb_equal(v, INT2FIX(0))) {
4572 v = subv(den, v);
4573 }
4574 return time_add(tobj, time, v, 1);
4575}
4576
4577/*
4578 * call-seq:
4579 * sec -> integer
4580 *
4581 * Returns the integer second of the minute for +self+,
4582 * in range (0..60):
4583 *
4584 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4585 * # => 2000-01-02 03:04:05 +000006
4586 * t.sec # => 5
4587 *
4588 * Note: the second value may be 60 when there is a
4589 * {leap second}[https://en.wikipedia.org/wiki/Leap_second].
4590 *
4591 * Related: Time#year, Time#mon, Time#min.
4592 */
4593
4594static VALUE
4595time_sec(VALUE time)
4596{
4597 struct time_object *tobj;
4598
4599 GetTimeval(time, tobj);
4600 MAKE_TM(time, tobj);
4601 return INT2FIX(tobj->vtm.sec);
4602}
4603
4604/*
4605 * call-seq:
4606 * min -> integer
4607 *
4608 * Returns the integer minute of the hour for +self+,
4609 * in range (0..59):
4610 *
4611 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4612 * # => 2000-01-02 03:04:05 +000006
4613 * t.min # => 4
4614 *
4615 * Related: Time#year, Time#mon, Time#sec.
4616 */
4617
4618static VALUE
4619time_min(VALUE time)
4620{
4621 struct time_object *tobj;
4622
4623 GetTimeval(time, tobj);
4624 MAKE_TM(time, tobj);
4625 return INT2FIX(tobj->vtm.min);
4626}
4627
4628/*
4629 * call-seq:
4630 * hour -> integer
4631 *
4632 * Returns the integer hour of the day for +self+,
4633 * in range (0..23):
4634 *
4635 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4636 * # => 2000-01-02 03:04:05 +000006
4637 * t.hour # => 3
4638 *
4639 * Related: Time#year, Time#mon, Time#min.
4640 */
4641
4642static VALUE
4643time_hour(VALUE time)
4644{
4645 struct time_object *tobj;
4646
4647 GetTimeval(time, tobj);
4648 MAKE_TM(time, tobj);
4649 return INT2FIX(tobj->vtm.hour);
4650}
4651
4652/*
4653 * call-seq:
4654 * mday -> integer
4655 *
4656 * Returns the integer day of the month for +self+,
4657 * in range (1..31):
4658 *
4659 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4660 * # => 2000-01-02 03:04:05 +000006
4661 * t.mday # => 2
4662 *
4663 * Time#day is an alias for Time#mday.
4664 *
4665 * Related: Time#year, Time#hour, Time#min.
4666 */
4667
4668static VALUE
4669time_mday(VALUE time)
4670{
4671 struct time_object *tobj;
4672
4673 GetTimeval(time, tobj);
4674 MAKE_TM(time, tobj);
4675 return INT2FIX(tobj->vtm.mday);
4676}
4677
4678/*
4679 * call-seq:
4680 * mon -> integer
4681 *
4682 * Returns the integer month of the year for +self+,
4683 * in range (1..12):
4684 *
4685 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4686 * # => 2000-01-02 03:04:05 +000006
4687 * t.mon # => 1
4688 *
4689 * Time#month is an alias for Time#mday.
4690 *
4691 * Related: Time#year, Time#hour, Time#min.
4692 */
4693
4694static VALUE
4695time_mon(VALUE time)
4696{
4697 struct time_object *tobj;
4698
4699 GetTimeval(time, tobj);
4700 MAKE_TM(time, tobj);
4701 return INT2FIX(tobj->vtm.mon);
4702}
4703
4704/*
4705 * call-seq:
4706 * year -> integer
4707 *
4708 * Returns the integer year for +self+:
4709 *
4710 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4711 * # => 2000-01-02 03:04:05 +000006
4712 * t.year # => 2000
4713 *
4714 * Related: Time#mon, Time#hour, Time#min.
4715 */
4716
4717static VALUE
4718time_year(VALUE time)
4719{
4720 struct time_object *tobj;
4721
4722 GetTimeval(time, tobj);
4723 MAKE_TM(time, tobj);
4724 return tobj->vtm.year;
4725}
4726
4727/*
4728 * call-seq:
4729 * wday -> integer
4730 *
4731 * Returns the integer day of the week for +self+,
4732 * in range (0..6), with Sunday as zero.
4733 *
4734 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4735 * # => 2000-01-02 03:04:05 +000006
4736 * t.wday # => 0
4737 * t.sunday? # => true
4738 *
4739 * Related: Time#year, Time#hour, Time#min.
4740 */
4741
4742static VALUE
4743time_wday(VALUE time)
4744{
4745 struct time_object *tobj;
4746
4747 GetTimeval(time, tobj);
4748 MAKE_TM_ENSURE(time, tobj, tobj->vtm.wday != VTM_WDAY_INITVAL);
4749 return INT2FIX((int)tobj->vtm.wday);
4750}
4751
4752#define wday_p(n) {\
4753 return RBOOL(time_wday(time) == INT2FIX(n)); \
4754}
4755
4756/*
4757 * call-seq:
4758 * sunday? -> true or false
4759 *
4760 * Returns +true+ if +self+ represents a Sunday, +false+ otherwise:
4761 *
4762 * t = Time.utc(2000, 1, 2) # => 2000-01-02 00:00:00 UTC
4763 * t.sunday? # => true
4764 *
4765 * Related: Time#monday?, Time#tuesday?, Time#wednesday?.
4766 */
4767
4768static VALUE
4769time_sunday(VALUE time)
4770{
4771 wday_p(0);
4772}
4773
4774/*
4775 * call-seq:
4776 * monday? -> true or false
4777 *
4778 * Returns +true+ if +self+ represents a Monday, +false+ otherwise:
4779 *
4780 * t = Time.utc(2000, 1, 3) # => 2000-01-03 00:00:00 UTC
4781 * t.monday? # => true
4782 *
4783 * Related: Time#tuesday?, Time#wednesday?, Time#thursday?.
4784 */
4785
4786static VALUE
4787time_monday(VALUE time)
4788{
4789 wday_p(1);
4790}
4791
4792/*
4793 * call-seq:
4794 * tuesday? -> true or false
4795 *
4796 * Returns +true+ if +self+ represents a Tuesday, +false+ otherwise:
4797 *
4798 * t = Time.utc(2000, 1, 4) # => 2000-01-04 00:00:00 UTC
4799 * t.tuesday? # => true
4800 *
4801 * Related: Time#wednesday?, Time#thursday?, Time#friday?.
4802 */
4803
4804static VALUE
4805time_tuesday(VALUE time)
4806{
4807 wday_p(2);
4808}
4809
4810/*
4811 * call-seq:
4812 * wednesday? -> true or false
4813 *
4814 * Returns +true+ if +self+ represents a Wednesday, +false+ otherwise:
4815 *
4816 * t = Time.utc(2000, 1, 5) # => 2000-01-05 00:00:00 UTC
4817 * t.wednesday? # => true
4818 *
4819 * Related: Time#thursday?, Time#friday?, Time#saturday?.
4820 */
4821
4822static VALUE
4823time_wednesday(VALUE time)
4824{
4825 wday_p(3);
4826}
4827
4828/*
4829 * call-seq:
4830 * thursday? -> true or false
4831 *
4832 * Returns +true+ if +self+ represents a Thursday, +false+ otherwise:
4833 *
4834 * t = Time.utc(2000, 1, 6) # => 2000-01-06 00:00:00 UTC
4835 * t.thursday? # => true
4836 *
4837 * Related: Time#friday?, Time#saturday?, Time#sunday?.
4838 */
4839
4840static VALUE
4841time_thursday(VALUE time)
4842{
4843 wday_p(4);
4844}
4845
4846/*
4847 * call-seq:
4848 * friday? -> true or false
4849 *
4850 * Returns +true+ if +self+ represents a Friday, +false+ otherwise:
4851 *
4852 * t = Time.utc(2000, 1, 7) # => 2000-01-07 00:00:00 UTC
4853 * t.friday? # => true
4854 *
4855 * Related: Time#saturday?, Time#sunday?, Time#monday?.
4856 */
4857
4858static VALUE
4859time_friday(VALUE time)
4860{
4861 wday_p(5);
4862}
4863
4864/*
4865 * call-seq:
4866 * saturday? -> true or false
4867 *
4868 * Returns +true+ if +self+ represents a Saturday, +false+ otherwise:
4869 *
4870 * t = Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC
4871 * t.saturday? # => true
4872 *
4873 * Related: Time#sunday?, Time#monday?, Time#tuesday?.
4874 */
4875
4876static VALUE
4877time_saturday(VALUE time)
4878{
4879 wday_p(6);
4880}
4881
4882/*
4883 * call-seq:
4884 * yday -> integer
4885 *
4886 * Returns the integer day of the year of +self+, in range (1..366).
4887 *
4888 * Time.new(2000, 1, 1).yday # => 1
4889 * Time.new(2000, 12, 31).yday # => 366
4890 */
4891
4892static VALUE
4893time_yday(VALUE time)
4894{
4895 struct time_object *tobj;
4896
4897 GetTimeval(time, tobj);
4898 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
4899 return INT2FIX(tobj->vtm.yday);
4900}
4901
4902/*
4903 * call-seq:
4904 * dst? -> true or false
4905 *
4906 * Returns +true+ if +self+ is in daylight saving time, +false+ otherwise:
4907 *
4908 * t = Time.local(2000, 1, 1) # => 2000-01-01 00:00:00 -0600
4909 * t.zone # => "Central Standard Time"
4910 * t.dst? # => false
4911 * t = Time.local(2000, 7, 1) # => 2000-07-01 00:00:00 -0500
4912 * t.zone # => "Central Daylight Time"
4913 * t.dst? # => true
4914 *
4915 * Time#isdst is an alias for Time#dst?.
4916 */
4917
4918static VALUE
4919time_isdst(VALUE time)
4920{
4921 struct time_object *tobj;
4922
4923 GetTimeval(time, tobj);
4924 MAKE_TM(time, tobj);
4925 if (tobj->vtm.isdst == VTM_ISDST_INITVAL) {
4926 rb_raise(rb_eRuntimeError, "isdst is not set yet");
4927 }
4928 return RBOOL(tobj->vtm.isdst);
4929}
4930
4931/*
4932 * call-seq:
4933 * time.zone -> string or timezone
4934 *
4935 * Returns the string name of the time zone for +self+:
4936 *
4937 * Time.utc(2000, 1, 1).zone # => "UTC"
4938 * Time.new(2000, 1, 1).zone # => "Central Standard Time"
4939 */
4940
4941static VALUE
4942time_zone(VALUE time)
4943{
4944 struct time_object *tobj;
4945 VALUE zone;
4946
4947 GetTimeval(time, tobj);
4948 MAKE_TM(time, tobj);
4949
4950 if (TZMODE_UTC_P(tobj)) {
4951 return rb_usascii_str_new_cstr("UTC");
4952 }
4953 zone = tobj->vtm.zone;
4954 if (NIL_P(zone))
4955 return Qnil;
4956
4957 if (RB_TYPE_P(zone, T_STRING))
4958 zone = rb_str_dup(zone);
4959 return zone;
4960}
4961
4962/*
4963 * call-seq:
4964 * utc_offset -> integer
4965 *
4966 * Returns the offset in seconds between the timezones of UTC and +self+:
4967 *
4968 * Time.utc(2000, 1, 1).utc_offset # => 0
4969 * Time.local(2000, 1, 1).utc_offset # => -21600 # -6*3600, or minus six hours.
4970 *
4971 * Time#gmt_offset and Time#gmtoff are aliases for Time#utc_offset.
4972 */
4973
4974VALUE
4976{
4977 struct time_object *tobj;
4978
4979 GetTimeval(time, tobj);
4980
4981 if (TZMODE_UTC_P(tobj)) {
4982 return INT2FIX(0);
4983 }
4984 else {
4985 MAKE_TM(time, tobj);
4986 return tobj->vtm.utc_offset;
4987 }
4988}
4989
4990/*
4991 * call-seq:
4992 * to_a -> array
4993 *
4994 * Returns a 10-element array of values representing +self+:
4995 *
4996 * Time.utc(2000, 1, 1).to_a
4997 * # => [0, 0, 0, 1, 1, 2000, 6, 1, false, "UTC"]
4998 * # [sec, min, hour, day, mon, year, wday, yday, dst?, zone]
4999 *
5000 * The returned array is suitable for use as an argument to Time.utc or Time.local
5001 * to create a new \Time object.
5002 *
5003 */
5004
5005static VALUE
5006time_to_a(VALUE time)
5007{
5008 struct time_object *tobj;
5009
5010 GetTimeval(time, tobj);
5011 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5012 return rb_ary_new3(10,
5013 INT2FIX(tobj->vtm.sec),
5014 INT2FIX(tobj->vtm.min),
5015 INT2FIX(tobj->vtm.hour),
5016 INT2FIX(tobj->vtm.mday),
5017 INT2FIX(tobj->vtm.mon),
5018 tobj->vtm.year,
5019 INT2FIX(tobj->vtm.wday),
5020 INT2FIX(tobj->vtm.yday),
5021 RBOOL(tobj->vtm.isdst),
5022 time_zone(time));
5023}
5024
5025/*
5026 * call-seq:
5027 * deconstruct_keys(array_of_names_or_nil) -> hash
5028 *
5029 * Returns a hash of the name/value pairs, to use in pattern matching.
5030 * Possible keys are: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>,
5031 * <tt>:yday</tt>, <tt>:wday</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>,
5032 * <tt>:subsec</tt>, <tt>:dst</tt>, <tt>:zone</tt>.
5033 *
5034 * Possible usages:
5035 *
5036 * t = Time.utc(2022, 10, 5, 21, 25, 30)
5037 *
5038 * if t in wday: 3, day: ..7 # uses deconstruct_keys underneath
5039 * puts "first Wednesday of the month"
5040 * end
5041 * #=> prints "first Wednesday of the month"
5042 *
5043 * case t
5044 * in year: ...2022
5045 * puts "too old"
5046 * in month: ..9
5047 * puts "quarter 1-3"
5048 * in wday: 1..5, month:
5049 * puts "working day in month #{month}"
5050 * end
5051 * #=> prints "working day in month 10"
5052 *
5053 * Note that deconstruction by pattern can also be combined with class check:
5054 *
5055 * if t in Time(wday: 3, day: ..7)
5056 * puts "first Wednesday of the month"
5057 * end
5058 *
5059 */
5060static VALUE
5061time_deconstruct_keys(VALUE time, VALUE keys)
5062{
5063 struct time_object *tobj;
5064 VALUE h;
5065 long i;
5066
5067 GetTimeval(time, tobj);
5068 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5069
5070 if (NIL_P(keys)) {
5071 h = rb_hash_new_with_size(11);
5072
5073 rb_hash_aset(h, sym_year, tobj->vtm.year);
5074 rb_hash_aset(h, sym_month, INT2FIX(tobj->vtm.mon));
5075 rb_hash_aset(h, sym_day, INT2FIX(tobj->vtm.mday));
5076 rb_hash_aset(h, sym_yday, INT2FIX(tobj->vtm.yday));
5077 rb_hash_aset(h, sym_wday, INT2FIX(tobj->vtm.wday));
5078 rb_hash_aset(h, sym_hour, INT2FIX(tobj->vtm.hour));
5079 rb_hash_aset(h, sym_min, INT2FIX(tobj->vtm.min));
5080 rb_hash_aset(h, sym_sec, INT2FIX(tobj->vtm.sec));
5081 rb_hash_aset(h, sym_subsec,
5082 quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
5083 rb_hash_aset(h, sym_dst, RBOOL(tobj->vtm.isdst));
5084 rb_hash_aset(h, sym_zone, time_zone(time));
5085
5086 return h;
5087 }
5088 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
5090 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
5091 rb_obj_class(keys));
5092
5093 }
5094
5095 h = rb_hash_new_with_size(RARRAY_LEN(keys));
5096
5097 for (i=0; i<RARRAY_LEN(keys); i++) {
5098 VALUE key = RARRAY_AREF(keys, i);
5099
5100 if (sym_year == key) rb_hash_aset(h, key, tobj->vtm.year);
5101 if (sym_month == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mon));
5102 if (sym_day == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mday));
5103 if (sym_yday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.yday));
5104 if (sym_wday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.wday));
5105 if (sym_hour == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.hour));
5106 if (sym_min == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.min));
5107 if (sym_sec == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.sec));
5108 if (sym_subsec == key) {
5109 rb_hash_aset(h, key, quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
5110 }
5111 if (sym_dst == key) rb_hash_aset(h, key, RBOOL(tobj->vtm.isdst));
5112 if (sym_zone == key) rb_hash_aset(h, key, time_zone(time));
5113 }
5114 return h;
5115}
5116
5117static VALUE
5118rb_strftime_alloc(const char *format, size_t format_len, rb_encoding *enc,
5119 VALUE time, struct vtm *vtm, wideval_t timew, int gmt)
5120{
5121 VALUE timev = Qnil;
5122 struct timespec ts;
5123
5124 if (!timew2timespec_exact(timew, &ts))
5125 timev = w2v(rb_time_unmagnify(timew));
5126
5127 if (NIL_P(timev)) {
5128 return rb_strftime_timespec(format, format_len, enc, time, vtm, &ts, gmt);
5129 }
5130 else {
5131 return rb_strftime(format, format_len, enc, time, vtm, timev, gmt);
5132 }
5133}
5134
5135static VALUE
5136strftime_cstr(const char *fmt, size_t len, VALUE time, rb_encoding *enc)
5137{
5138 struct time_object *tobj;
5139 VALUE str;
5140
5141 GetTimeval(time, tobj);
5142 MAKE_TM(time, tobj);
5143 str = rb_strftime_alloc(fmt, len, enc, time, &tobj->vtm, tobj->timew, TZMODE_UTC_P(tobj));
5144 if (!str) rb_raise(rb_eArgError, "invalid format: %s", fmt);
5145 return str;
5146}
5147
5148/*
5149 * call-seq:
5150 * strftime(format_string) -> string
5151 *
5152 * Returns a string representation of +self+,
5153 * formatted according to the given string +format+.
5154 * See {Formats for Dates and Times}[rdoc-ref:strftime_formatting.rdoc].
5155 */
5156
5157static VALUE
5158time_strftime(VALUE time, VALUE format)
5159{
5160 struct time_object *tobj;
5161 const char *fmt;
5162 long len;
5163 rb_encoding *enc;
5164 VALUE tmp;
5165
5166 GetTimeval(time, tobj);
5167 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5168 StringValue(format);
5169 if (!rb_enc_str_asciicompat_p(format)) {
5170 rb_raise(rb_eArgError, "format should have ASCII compatible encoding");
5171 }
5172 tmp = rb_str_tmp_frozen_acquire(format);
5173 fmt = RSTRING_PTR(tmp);
5174 len = RSTRING_LEN(tmp);
5175 enc = rb_enc_get(format);
5176 if (len == 0) {
5177 rb_warning("strftime called with empty format string");
5178 return rb_enc_str_new(0, 0, enc);
5179 }
5180 else {
5181 VALUE str = rb_strftime_alloc(fmt, len, enc, time, &tobj->vtm, tobj->timew,
5182 TZMODE_UTC_P(tobj));
5183 rb_str_tmp_frozen_release(format, tmp);
5184 if (!str) rb_raise(rb_eArgError, "invalid format: %"PRIsVALUE, format);
5185 return str;
5186 }
5187}
5188
5189int ruby_marshal_write_long(long x, char *buf);
5190
5191enum {base_dump_size = 8};
5192
5193/* :nodoc: */
5194static VALUE
5195time_mdump(VALUE time)
5196{
5197 struct time_object *tobj;
5198 unsigned long p, s;
5199 char buf[base_dump_size + sizeof(long) + 1];
5200 int i;
5201 VALUE str;
5202
5203 struct vtm vtm;
5204 long year;
5205 long usec, nsec;
5206 VALUE subsecx, nano, subnano, v, zone;
5207
5208 VALUE year_extend = Qnil;
5209 const int max_year = 1900+0xffff;
5210
5211 GetTimeval(time, tobj);
5212
5213 gmtimew(tobj->timew, &vtm);
5214
5215 if (FIXNUM_P(vtm.year)) {
5216 year = FIX2LONG(vtm.year);
5217 if (year > max_year) {
5218 year_extend = INT2FIX(year - max_year);
5219 year = max_year;
5220 }
5221 else if (year < 1900) {
5222 year_extend = LONG2NUM(1900 - year);
5223 year = 1900;
5224 }
5225 }
5226 else {
5227 if (rb_int_positive_p(vtm.year)) {
5228 year_extend = rb_int_minus(vtm.year, INT2FIX(max_year));
5229 year = max_year;
5230 }
5231 else {
5232 year_extend = rb_int_minus(INT2FIX(1900), vtm.year);
5233 year = 1900;
5234 }
5235 }
5236
5237 subsecx = vtm.subsecx;
5238
5239 nano = mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE));
5240 divmodv(nano, INT2FIX(1), &v, &subnano);
5241 nsec = FIX2LONG(v);
5242 usec = nsec / 1000;
5243 nsec = nsec % 1000;
5244
5245 nano = addv(LONG2FIX(nsec), subnano);
5246
5247 p = 0x1UL << 31 | /* 1 */
5248 TZMODE_UTC_P(tobj) << 30 | /* 1 */
5249 (year-1900) << 14 | /* 16 */
5250 (vtm.mon-1) << 10 | /* 4 */
5251 vtm.mday << 5 | /* 5 */
5252 vtm.hour; /* 5 */
5253 s = (unsigned long)vtm.min << 26 | /* 6 */
5254 vtm.sec << 20 | /* 6 */
5255 usec; /* 20 */
5256
5257 for (i=0; i<4; i++) {
5258 buf[i] = (unsigned char)p;
5259 p = RSHIFT(p, 8);
5260 }
5261 for (i=4; i<8; i++) {
5262 buf[i] = (unsigned char)s;
5263 s = RSHIFT(s, 8);
5264 }
5265
5266 if (!NIL_P(year_extend)) {
5267 /*
5268 * Append extended year distance from 1900..(1900+0xffff). In
5269 * each cases, there is no sign as the value is positive. The
5270 * format is length (marshaled long) + little endian packed
5271 * binary (like as Integer).
5272 */
5273 size_t ysize = rb_absint_size(year_extend, NULL);
5274 char *p, *const buf_year_extend = buf + base_dump_size;
5275 if (ysize > LONG_MAX ||
5276 (i = ruby_marshal_write_long((long)ysize, buf_year_extend)) < 0) {
5277 rb_raise(rb_eArgError, "year too %s to marshal: %"PRIsVALUE" UTC",
5278 (year == 1900 ? "small" : "big"), vtm.year);
5279 }
5280 i += base_dump_size;
5281 str = rb_str_new(NULL, i + ysize);
5282 p = RSTRING_PTR(str);
5283 memcpy(p, buf, i);
5284 p += i;
5285 rb_integer_pack(year_extend, p, ysize, 1, 0, INTEGER_PACK_LITTLE_ENDIAN);
5286 }
5287 else {
5288 str = rb_str_new(buf, base_dump_size);
5289 }
5290 rb_copy_generic_ivar(str, time);
5291 if (!rb_equal(nano, INT2FIX(0))) {
5292 if (RB_TYPE_P(nano, T_RATIONAL)) {
5293 rb_ivar_set(str, id_nano_num, RRATIONAL(nano)->num);
5294 rb_ivar_set(str, id_nano_den, RRATIONAL(nano)->den);
5295 }
5296 else {
5297 rb_ivar_set(str, id_nano_num, nano);
5298 rb_ivar_set(str, id_nano_den, INT2FIX(1));
5299 }
5300 }
5301 if (nsec) { /* submicro is only for Ruby 1.9.1 compatibility */
5302 /*
5303 * submicro is formatted in fixed-point packed BCD (without sign).
5304 * It represent digits under microsecond.
5305 * For nanosecond resolution, 3 digits (2 bytes) are used.
5306 * However it can be longer.
5307 * Extra digits are ignored for loading.
5308 */
5309 char buf[2];
5310 int len = (int)sizeof(buf);
5311 buf[1] = (char)((nsec % 10) << 4);
5312 nsec /= 10;
5313 buf[0] = (char)(nsec % 10);
5314 nsec /= 10;
5315 buf[0] |= (char)((nsec % 10) << 4);
5316 if (buf[1] == 0)
5317 len = 1;
5318 rb_ivar_set(str, id_submicro, rb_str_new(buf, len));
5319 }
5320 if (!TZMODE_UTC_P(tobj)) {
5321 VALUE off = rb_time_utc_offset(time), div, mod;
5322 divmodv(off, INT2FIX(1), &div, &mod);
5323 if (rb_equal(mod, INT2FIX(0)))
5324 off = rb_Integer(div);
5325 rb_ivar_set(str, id_offset, off);
5326 }
5327 zone = tobj->vtm.zone;
5328 if (maybe_tzobj_p(zone)) {
5329 zone = rb_funcallv(zone, id_name, 0, 0);
5330 }
5331 rb_ivar_set(str, id_zone, zone);
5332 return str;
5333}
5334
5335/* :nodoc: */
5336static VALUE
5337time_dump(int argc, VALUE *argv, VALUE time)
5338{
5339 VALUE str;
5340
5341 rb_check_arity(argc, 0, 1);
5342 str = time_mdump(time);
5343
5344 return str;
5345}
5346
5347static VALUE
5348mload_findzone(VALUE arg)
5349{
5350 VALUE *argp = (VALUE *)arg;
5351 VALUE time = argp[0], zone = argp[1];
5352 return find_timezone(time, zone);
5353}
5354
5355static VALUE
5356mload_zone(VALUE time, VALUE zone)
5357{
5358 VALUE z, args[2];
5359 args[0] = time;
5360 args[1] = zone;
5361 z = rb_rescue(mload_findzone, (VALUE)args, 0, Qnil);
5362 if (NIL_P(z)) return rb_fstring(zone);
5363 if (RB_TYPE_P(z, T_STRING)) return rb_fstring(z);
5364 return z;
5365}
5366
5367long ruby_marshal_read_long(const char **buf, long len);
5368
5369/* :nodoc: */
5370static VALUE
5371time_mload(VALUE time, VALUE str)
5372{
5373 struct time_object *tobj;
5374 unsigned long p, s;
5375 time_t sec;
5376 long usec;
5377 unsigned char *buf;
5378 struct vtm vtm;
5379 int i, gmt;
5380 long nsec;
5381 VALUE submicro, nano_num, nano_den, offset, zone, year;
5382 wideval_t timew;
5383
5384 time_modify(time);
5385
5386#define get_attr(attr, iffound) \
5387 attr = rb_attr_delete(str, id_##attr); \
5388 if (!NIL_P(attr)) { \
5389 iffound; \
5390 }
5391
5392 get_attr(nano_num, {});
5393 get_attr(nano_den, {});
5394 get_attr(submicro, {});
5395 get_attr(offset, (offset = rb_rescue(validate_utc_offset, offset, 0, Qnil)));
5396 get_attr(zone, (zone = rb_rescue(validate_zone_name, zone, 0, Qnil)));
5397 get_attr(year, {});
5398
5399#undef get_attr
5400
5401 rb_copy_generic_ivar(time, str);
5402
5403 StringValue(str);
5404 buf = (unsigned char *)RSTRING_PTR(str);
5405 if (RSTRING_LEN(str) < base_dump_size) {
5406 goto invalid_format;
5407 }
5408
5409 p = s = 0;
5410 for (i=0; i<4; i++) {
5411 p |= (unsigned long)buf[i]<<(8*i);
5412 }
5413 for (i=4; i<8; i++) {
5414 s |= (unsigned long)buf[i]<<(8*(i-4));
5415 }
5416
5417 if ((p & (1UL<<31)) == 0) {
5418 gmt = 0;
5419 offset = Qnil;
5420 sec = p;
5421 usec = s;
5422 nsec = usec * 1000;
5423 timew = wadd(rb_time_magnify(TIMET2WV(sec)), wmulquoll(WINT2FIXWV(usec), TIME_SCALE, 1000000));
5424 }
5425 else {
5426 p &= ~(1UL<<31);
5427 gmt = (int)((p >> 30) & 0x1);
5428
5429 if (NIL_P(year)) {
5430 year = INT2FIX(((int)(p >> 14) & 0xffff) + 1900);
5431 }
5432 if (RSTRING_LEN(str) > base_dump_size) {
5433 long len = RSTRING_LEN(str) - base_dump_size;
5434 long ysize = 0;
5435 VALUE year_extend;
5436 const char *ybuf = (const char *)(buf += base_dump_size);
5437 ysize = ruby_marshal_read_long(&ybuf, len);
5438 len -= ybuf - (const char *)buf;
5439 if (ysize < 0 || ysize > len) goto invalid_format;
5440 year_extend = rb_integer_unpack(ybuf, ysize, 1, 0, INTEGER_PACK_LITTLE_ENDIAN);
5441 if (year == INT2FIX(1900)) {
5442 year = rb_int_minus(year, year_extend);
5443 }
5444 else {
5445 year = rb_int_plus(year, year_extend);
5446 }
5447 }
5448 unsigned int mon = ((int)(p >> 10) & 0xf); /* 0...12 */
5449 if (mon >= 12) {
5450 mon -= 12;
5451 year = addv(year, LONG2FIX(1));
5452 }
5453 vtm.year = year;
5454 vtm.mon = mon + 1;
5455 vtm.mday = (int)(p >> 5) & 0x1f;
5456 vtm.hour = (int) p & 0x1f;
5457 vtm.min = (int)(s >> 26) & 0x3f;
5458 vtm.sec = (int)(s >> 20) & 0x3f;
5459 vtm.utc_offset = INT2FIX(0);
5460 vtm.yday = vtm.wday = 0;
5461 vtm.isdst = 0;
5462 vtm.zone = str_empty;
5463
5464 usec = (long)(s & 0xfffff);
5465 nsec = usec * 1000;
5466
5467
5468 vtm.subsecx = mulquov(LONG2FIX(nsec), INT2FIX(TIME_SCALE), LONG2FIX(1000000000));
5469 if (nano_num != Qnil) {
5470 VALUE nano = quov(num_exact(nano_num), num_exact(nano_den));
5471 vtm.subsecx = addv(vtm.subsecx, mulquov(nano, INT2FIX(TIME_SCALE), LONG2FIX(1000000000)));
5472 }
5473 else if (submicro != Qnil) { /* for Ruby 1.9.1 compatibility */
5474 unsigned char *ptr;
5475 long len;
5476 int digit;
5477 ptr = (unsigned char*)StringValuePtr(submicro);
5478 len = RSTRING_LEN(submicro);
5479 nsec = 0;
5480 if (0 < len) {
5481 if (10 <= (digit = ptr[0] >> 4)) goto end_submicro;
5482 nsec += digit * 100;
5483 if (10 <= (digit = ptr[0] & 0xf)) goto end_submicro;
5484 nsec += digit * 10;
5485 }
5486 if (1 < len) {
5487 if (10 <= (digit = ptr[1] >> 4)) goto end_submicro;
5488 nsec += digit;
5489 }
5490 vtm.subsecx = addv(vtm.subsecx, mulquov(LONG2FIX(nsec), INT2FIX(TIME_SCALE), LONG2FIX(1000000000)));
5491end_submicro: ;
5492 }
5493 timew = timegmw(&vtm);
5494 }
5495
5496 GetNewTimeval(time, tobj);
5497 TZMODE_SET_LOCALTIME(tobj);
5498 tobj->tm_got = 0;
5499 tobj->timew = timew;
5500 if (gmt) {
5501 TZMODE_SET_UTC(tobj);
5502 }
5503 else if (!NIL_P(offset)) {
5504 time_set_utc_offset(time, offset);
5505 time_fixoff(time);
5506 }
5507 if (!NIL_P(zone)) {
5508 zone = mload_zone(time, zone);
5509 tobj->vtm.zone = zone;
5510 zone_localtime(zone, time);
5511 }
5512
5513 return time;
5514
5515 invalid_format:
5516 rb_raise(rb_eTypeError, "marshaled time format differ");
5518}
5519
5520/* :nodoc: */
5521static VALUE
5522time_load(VALUE klass, VALUE str)
5523{
5524 VALUE time = time_s_alloc(klass);
5525
5526 time_mload(time, str);
5527 return time;
5528}
5529
5530/* :nodoc:*/
5531/* Document-class: Time::tm
5532 *
5533 * A container class for timezone conversion.
5534 */
5535
5536/*
5537 * call-seq:
5538 *
5539 * Time::tm.from_time(t) -> tm
5540 *
5541 * Creates new Time::tm object from a Time object.
5542 */
5543
5544static VALUE
5545tm_from_time(VALUE klass, VALUE time)
5546{
5547 struct time_object *tobj;
5548 struct vtm vtm, *v;
5549#if TM_IS_TIME
5550 VALUE tm;
5551 struct time_object *ttm;
5552
5553 GetTimeval(time, tobj);
5554 tm = time_s_alloc(klass);
5555 ttm = DATA_PTR(tm);
5556 v = &vtm;
5557 GMTIMEW(ttm->timew = tobj->timew, v);
5558 ttm->timew = wsub(ttm->timew, v->subsecx);
5559 v->subsecx = INT2FIX(0);
5560 v->zone = Qnil;
5561 ttm->vtm = *v;
5562 ttm->tm_got = 1;
5563 TZMODE_SET_UTC(ttm);
5564 return tm;
5565#else
5566 VALUE args[8];
5567 int i = 0;
5568
5569 GetTimeval(time, tobj);
5570 if (tobj->tm_got && TZMODE_UTC_P(tobj))
5571 v = &tobj->vtm;
5572 else
5573 GMTIMEW(tobj->timew, v = &vtm);
5574 args[i++] = v->year;
5575 args[i++] = INT2FIX(v->mon);
5576 args[i++] = INT2FIX(v->mday);
5577 args[i++] = INT2FIX(v->hour);
5578 args[i++] = INT2FIX(v->min);
5579 args[i++] = INT2FIX(v->sec);
5580 switch (v->isdst) {
5581 case 0: args[i++] = Qfalse; break;
5582 case 1: args[i++] = Qtrue; break;
5583 default: args[i++] = Qnil; break;
5584 }
5585 args[i++] = w2v(rb_time_unmagnify(tobj->timew));
5586 return rb_class_new_instance(i, args, klass);
5587#endif
5588}
5589
5590/*
5591 * call-seq:
5592 *
5593 * Time::tm.new(year, month=nil, day=nil, hour=nil, min=nil, sec=nil, zone=nil) -> tm
5594 *
5595 * Creates new Time::tm object.
5596 */
5597
5598static VALUE
5599tm_initialize(int argc, VALUE *argv, VALUE tm)
5600{
5601 struct vtm vtm;
5602 wideval_t t;
5603
5604 if (rb_check_arity(argc, 1, 7) > 6) argc = 6;
5605 time_arg(argc, argv, &vtm);
5606 t = timegmw(&vtm);
5607 {
5608#if TM_IS_TIME
5609 struct time_object *tobj = DATA_PTR(tm);
5610 TZMODE_SET_UTC(tobj);
5611 tobj->timew = t;
5612 tobj->vtm = vtm;
5613#else
5614 int i = 0;
5615 RSTRUCT_SET(tm, i++, INT2FIX(vtm.sec));
5616 RSTRUCT_SET(tm, i++, INT2FIX(vtm.min));
5617 RSTRUCT_SET(tm, i++, INT2FIX(vtm.hour));
5618 RSTRUCT_SET(tm, i++, INT2FIX(vtm.mday));
5619 RSTRUCT_SET(tm, i++, INT2FIX(vtm.mon));
5620 RSTRUCT_SET(tm, i++, vtm.year);
5621 RSTRUCT_SET(tm, i++, w2v(rb_time_unmagnify(t)));
5622#endif
5623 }
5624 return tm;
5625}
5626
5627/* call-seq:
5628 *
5629 * tm.to_time -> time
5630 *
5631 * Returns a new Time object.
5632 */
5633
5634static VALUE
5635tm_to_time(VALUE tm)
5636{
5637#if TM_IS_TIME
5638 struct time_object *torig = get_timeval(tm);
5639 VALUE dup = time_s_alloc(rb_cTime);
5640 struct time_object *tobj = DATA_PTR(dup);
5641 *tobj = *torig;
5642 return dup;
5643#else
5644 VALUE t[6];
5645 const VALUE *p = RSTRUCT_CONST_PTR(tm);
5646 int i;
5647
5648 for (i = 0; i < numberof(t); ++i) {
5649 t[i] = p[numberof(t) - 1 - i];
5650 }
5651 return time_s_mkutc(numberof(t), t, rb_cTime);
5652#endif
5653}
5654
5655#if !TM_IS_TIME
5656static VALUE
5657tm_zero(VALUE tm)
5658{
5659 return INT2FIX(0);
5660}
5661
5662#define tm_subsec tm_zero
5663#define tm_utc_offset tm_zero
5664
5665static VALUE
5666tm_isdst(VALUE tm)
5667{
5668 return Qfalse;
5669}
5670
5671static VALUE
5672tm_to_s(VALUE tm)
5673{
5674 const VALUE *p = RSTRUCT_CONST_PTR(tm);
5675
5676 return rb_sprintf("%.4"PRIsVALUE"-%.2"PRIsVALUE"-%.2"PRIsVALUE" "
5677 "%.2"PRIsVALUE":%.2"PRIsVALUE":%.2"PRIsVALUE" "
5678 "UTC",
5679 p[5], p[4], p[3], p[2], p[1], p[0]);
5680}
5681#else
5682static VALUE
5683tm_plus(VALUE tm, VALUE offset)
5684{
5685 return time_add0(rb_obj_class(tm), get_timeval(tm), tm, offset, +1);
5686}
5687
5688static VALUE
5689tm_minus(VALUE tm, VALUE offset)
5690{
5691 return time_add0(rb_obj_class(tm), get_timeval(tm), tm, offset, -1);
5692}
5693#endif
5694
5695static VALUE
5696Init_tm(VALUE outer, const char *name)
5697{
5698 /* :stopdoc:*/
5699 VALUE tm;
5700#if TM_IS_TIME
5701 tm = rb_define_class_under(outer, name, rb_cObject);
5702 rb_define_alloc_func(tm, time_s_alloc);
5703 rb_define_method(tm, "sec", time_sec, 0);
5704 rb_define_method(tm, "min", time_min, 0);
5705 rb_define_method(tm, "hour", time_hour, 0);
5706 rb_define_method(tm, "mday", time_mday, 0);
5707 rb_define_method(tm, "day", time_mday, 0);
5708 rb_define_method(tm, "mon", time_mon, 0);
5709 rb_define_method(tm, "month", time_mon, 0);
5710 rb_define_method(tm, "year", time_year, 0);
5711 rb_define_method(tm, "isdst", time_isdst, 0);
5712 rb_define_method(tm, "dst?", time_isdst, 0);
5713 rb_define_method(tm, "zone", time_zone, 0);
5714 rb_define_method(tm, "gmtoff", rb_time_utc_offset, 0);
5715 rb_define_method(tm, "gmt_offset", rb_time_utc_offset, 0);
5716 rb_define_method(tm, "utc_offset", rb_time_utc_offset, 0);
5717 rb_define_method(tm, "utc?", time_utc_p, 0);
5718 rb_define_method(tm, "gmt?", time_utc_p, 0);
5719 rb_define_method(tm, "to_s", time_to_s, 0);
5720 rb_define_method(tm, "inspect", time_inspect, 0);
5721 rb_define_method(tm, "to_a", time_to_a, 0);
5722 rb_define_method(tm, "tv_sec", time_to_i, 0);
5723 rb_define_method(tm, "tv_usec", time_usec, 0);
5724 rb_define_method(tm, "usec", time_usec, 0);
5725 rb_define_method(tm, "tv_nsec", time_nsec, 0);
5726 rb_define_method(tm, "nsec", time_nsec, 0);
5727 rb_define_method(tm, "subsec", time_subsec, 0);
5728 rb_define_method(tm, "to_i", time_to_i, 0);
5729 rb_define_method(tm, "to_f", time_to_f, 0);
5730 rb_define_method(tm, "to_r", time_to_r, 0);
5731 rb_define_method(tm, "+", tm_plus, 1);
5732 rb_define_method(tm, "-", tm_minus, 1);
5733#else
5734 tm = rb_struct_define_under(outer, "tm",
5735 "sec", "min", "hour",
5736 "mday", "mon", "year",
5737 "to_i", NULL);
5738 rb_define_method(tm, "subsec", tm_subsec, 0);
5739 rb_define_method(tm, "utc_offset", tm_utc_offset, 0);
5740 rb_define_method(tm, "to_s", tm_to_s, 0);
5741 rb_define_method(tm, "inspect", tm_to_s, 0);
5742 rb_define_method(tm, "isdst", tm_isdst, 0);
5743 rb_define_method(tm, "dst?", tm_isdst, 0);
5744#endif
5745 rb_define_method(tm, "initialize", tm_initialize, -1);
5746 rb_define_method(tm, "utc", tm_to_time, 0);
5747 rb_alias(tm, rb_intern_const("to_time"), rb_intern_const("utc"));
5748 rb_define_singleton_method(tm, "from_time", tm_from_time, 1);
5749 /* :startdoc:*/
5750
5751 return tm;
5752}
5753
5754VALUE
5755rb_time_zone_abbreviation(VALUE zone, VALUE time)
5756{
5757 VALUE tm, abbr, strftime_args[2];
5758
5759 abbr = rb_check_string_type(zone);
5760 if (!NIL_P(abbr)) return abbr;
5761
5762 tm = tm_from_time(rb_cTimeTM, time);
5763 abbr = rb_check_funcall(zone, rb_intern("abbr"), 1, &tm);
5764 if (!UNDEF_P(abbr)) {
5765 goto found;
5766 }
5767#ifdef SUPPORT_TZINFO_ZONE_ABBREVIATION
5768 abbr = rb_check_funcall(zone, rb_intern("period_for_utc"), 1, &tm);
5769 if (!UNDEF_P(abbr)) {
5770 abbr = rb_funcallv(abbr, rb_intern("abbreviation"), 0, 0);
5771 goto found;
5772 }
5773#endif
5774 strftime_args[0] = rb_fstring_lit("%Z");
5775 strftime_args[1] = tm;
5776 abbr = rb_check_funcall(zone, rb_intern("strftime"), 2, strftime_args);
5777 if (!UNDEF_P(abbr)) {
5778 goto found;
5779 }
5780 abbr = rb_check_funcall_default(zone, idName, 0, 0, Qnil);
5781 found:
5782 return rb_obj_as_string(abbr);
5783}
5784
5785/* Internal Details:
5786 *
5787 * Since Ruby 1.9.2, Time implementation uses a signed 63 bit integer or
5788 * Integer(T_BIGNUM), Rational.
5789 * The integer is a number of nanoseconds since the _Epoch_ which can
5790 * represent 1823-11-12 to 2116-02-20.
5791 * When Integer(T_BIGNUM) or Rational is used (before 1823, after 2116, under
5792 * nanosecond), Time works slower than when integer is used.
5793 */
5794
5795//
5796void
5797Init_Time(void)
5798{
5799 id_submicro = rb_intern_const("submicro");
5800 id_nano_num = rb_intern_const("nano_num");
5801 id_nano_den = rb_intern_const("nano_den");
5802 id_offset = rb_intern_const("offset");
5803 id_zone = rb_intern_const("zone");
5804 id_nanosecond = rb_intern_const("nanosecond");
5805 id_microsecond = rb_intern_const("microsecond");
5806 id_millisecond = rb_intern_const("millisecond");
5807 id_nsec = rb_intern_const("nsec");
5808 id_usec = rb_intern_const("usec");
5809 id_local_to_utc = rb_intern_const("local_to_utc");
5810 id_utc_to_local = rb_intern_const("utc_to_local");
5811 id_year = rb_intern_const("year");
5812 id_mon = rb_intern_const("mon");
5813 id_mday = rb_intern_const("mday");
5814 id_hour = rb_intern_const("hour");
5815 id_min = rb_intern_const("min");
5816 id_sec = rb_intern_const("sec");
5817 id_isdst = rb_intern_const("isdst");
5818 id_find_timezone = rb_intern_const("find_timezone");
5819
5820 sym_year = ID2SYM(rb_intern_const("year"));
5821 sym_month = ID2SYM(rb_intern_const("month"));
5822 sym_yday = ID2SYM(rb_intern_const("yday"));
5823 sym_wday = ID2SYM(rb_intern_const("wday"));
5824 sym_day = ID2SYM(rb_intern_const("day"));
5825 sym_hour = ID2SYM(rb_intern_const("hour"));
5826 sym_min = ID2SYM(rb_intern_const("min"));
5827 sym_sec = ID2SYM(rb_intern_const("sec"));
5828 sym_subsec = ID2SYM(rb_intern_const("subsec"));
5829 sym_dst = ID2SYM(rb_intern_const("dst"));
5830 sym_zone = ID2SYM(rb_intern_const("zone"));
5831
5832 str_utc = rb_fstring_lit("UTC");
5833 rb_gc_register_mark_object(str_utc);
5834 str_empty = rb_fstring_lit("");
5835 rb_gc_register_mark_object(str_empty);
5836
5837 rb_cTime = rb_define_class("Time", rb_cObject);
5840
5841 rb_define_alloc_func(rb_cTime, time_s_alloc);
5842 rb_define_singleton_method(rb_cTime, "utc", time_s_mkutc, -1);
5843 rb_define_singleton_method(rb_cTime, "local", time_s_mktime, -1);
5844 rb_define_alias(scTime, "gm", "utc");
5845 rb_define_alias(scTime, "mktime", "local");
5846
5847 rb_define_method(rb_cTime, "to_i", time_to_i, 0);
5848 rb_define_method(rb_cTime, "to_f", time_to_f, 0);
5849 rb_define_method(rb_cTime, "to_r", time_to_r, 0);
5850 rb_define_method(rb_cTime, "<=>", time_cmp, 1);
5851 rb_define_method(rb_cTime, "eql?", time_eql, 1);
5852 rb_define_method(rb_cTime, "hash", time_hash, 0);
5853 rb_define_method(rb_cTime, "initialize_copy", time_init_copy, 1);
5854
5855 rb_define_method(rb_cTime, "localtime", time_localtime_m, -1);
5856 rb_define_method(rb_cTime, "gmtime", time_gmtime, 0);
5857 rb_define_method(rb_cTime, "utc", time_gmtime, 0);
5858 rb_define_method(rb_cTime, "getlocal", time_getlocaltime, -1);
5859 rb_define_method(rb_cTime, "getgm", time_getgmtime, 0);
5860 rb_define_method(rb_cTime, "getutc", time_getgmtime, 0);
5861
5862 rb_define_method(rb_cTime, "ctime", time_asctime, 0);
5863 rb_define_method(rb_cTime, "asctime", time_asctime, 0);
5864 rb_define_method(rb_cTime, "to_s", time_to_s, 0);
5865 rb_define_method(rb_cTime, "inspect", time_inspect, 0);
5866 rb_define_method(rb_cTime, "to_a", time_to_a, 0);
5867 rb_define_method(rb_cTime, "deconstruct_keys", time_deconstruct_keys, 1);
5868
5869 rb_define_method(rb_cTime, "+", time_plus, 1);
5870 rb_define_method(rb_cTime, "-", time_minus, 1);
5871
5872 rb_define_method(rb_cTime, "round", time_round, -1);
5873 rb_define_method(rb_cTime, "floor", time_floor, -1);
5874 rb_define_method(rb_cTime, "ceil", time_ceil, -1);
5875
5876 rb_define_method(rb_cTime, "sec", time_sec, 0);
5877 rb_define_method(rb_cTime, "min", time_min, 0);
5878 rb_define_method(rb_cTime, "hour", time_hour, 0);
5879 rb_define_method(rb_cTime, "mday", time_mday, 0);
5880 rb_define_method(rb_cTime, "day", time_mday, 0);
5881 rb_define_method(rb_cTime, "mon", time_mon, 0);
5882 rb_define_method(rb_cTime, "month", time_mon, 0);
5883 rb_define_method(rb_cTime, "year", time_year, 0);
5884 rb_define_method(rb_cTime, "wday", time_wday, 0);
5885 rb_define_method(rb_cTime, "yday", time_yday, 0);
5886 rb_define_method(rb_cTime, "isdst", time_isdst, 0);
5887 rb_define_method(rb_cTime, "dst?", time_isdst, 0);
5888 rb_define_method(rb_cTime, "zone", time_zone, 0);
5889 rb_define_method(rb_cTime, "gmtoff", rb_time_utc_offset, 0);
5890 rb_define_method(rb_cTime, "gmt_offset", rb_time_utc_offset, 0);
5891 rb_define_method(rb_cTime, "utc_offset", rb_time_utc_offset, 0);
5892
5893 rb_define_method(rb_cTime, "utc?", time_utc_p, 0);
5894 rb_define_method(rb_cTime, "gmt?", time_utc_p, 0);
5895
5896 rb_define_method(rb_cTime, "sunday?", time_sunday, 0);
5897 rb_define_method(rb_cTime, "monday?", time_monday, 0);
5898 rb_define_method(rb_cTime, "tuesday?", time_tuesday, 0);
5899 rb_define_method(rb_cTime, "wednesday?", time_wednesday, 0);
5900 rb_define_method(rb_cTime, "thursday?", time_thursday, 0);
5901 rb_define_method(rb_cTime, "friday?", time_friday, 0);
5902 rb_define_method(rb_cTime, "saturday?", time_saturday, 0);
5903
5904 rb_define_method(rb_cTime, "tv_sec", time_to_i, 0);
5905 rb_define_method(rb_cTime, "tv_usec", time_usec, 0);
5906 rb_define_method(rb_cTime, "usec", time_usec, 0);
5907 rb_define_method(rb_cTime, "tv_nsec", time_nsec, 0);
5908 rb_define_method(rb_cTime, "nsec", time_nsec, 0);
5909 rb_define_method(rb_cTime, "subsec", time_subsec, 0);
5910
5911 rb_define_method(rb_cTime, "strftime", time_strftime, 1);
5912
5913 /* methods for marshaling */
5914 rb_define_private_method(rb_cTime, "_dump", time_dump, -1);
5915 rb_define_private_method(scTime, "_load", time_load, 1);
5916#if 0
5917 /* Time will support marshal_dump and marshal_load in the future (1.9 maybe) */
5918 rb_define_private_method(rb_cTime, "marshal_dump", time_mdump, 0);
5919 rb_define_private_method(rb_cTime, "marshal_load", time_mload, 1);
5920#endif
5921
5922 if (debug_find_time_numguess) {
5923 rb_define_hooked_variable("$find_time_numguess", (VALUE *)&find_time_numguess,
5924 find_time_numguess_getter, NULL);
5925 }
5926
5927 rb_cTimeTM = Init_tm(rb_cTime, "tm");
5928}
5929
5930#include "timev.rbinc"
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
Definition: cxxanyargs.hpp:670
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
Definition: cxxanyargs.hpp:685
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
Definition: cxxanyargs.hpp:677
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition: class.c:1090
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition: class.c:888
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition: class.c:2201
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:920
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition: class.c:2249
#define TYPE(_)
Old name of rb_type.
Definition: value_type.h:107
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition: value_type.h:87
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition: object.h:41
#define ISSPACE
Old name of rb_isspace.
Definition: ctype.h:88
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition: double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition: value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition: long.h:48
#define T_NIL
Old name of RUBY_T_NIL.
Definition: value_type.h:72
#define ID2SYM
Old name of RB_ID2SYM.
Definition: symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition: value_type.h:57
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition: value_type.h:79
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition: value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition: assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition: globals.h:203
#define LONG2FIX
Old name of RB_INT2FIX.
Definition: long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition: int.h:41
#define ISDIGIT
Old name of rb_isdigit.
Definition: ctype.h:93
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition: assume.h:27
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition: value_type.h:76
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition: array.h:652
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition: long.h:50
#define STRNCASECMP
Old name of st_locale_insensitive_strncasecmp.
Definition: ctype.h:103
#define ISASCII
Old name of rb_isascii.
Definition: ctype.h:85
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition: long_long.h:31
#define FIXNUM_MIN
Old name of RUBY_FIXNUM_MIN.
Definition: fixnum.h:27
#define Qtrue
Old name of RUBY_Qtrue.
#define NUM2INT
Old name of RB_NUM2INT.
Definition: int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition: int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition: long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition: value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define DBL2NUM
Old name of rb_float_new.
Definition: double.h:29
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition: long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition: symbol.h:47
#define NUM2SIZET
Old name of RB_NUM2SIZE.
Definition: size_t.h:61
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
Definition: error.c:3148
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition: eval.c:684
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
Definition: error.c:1041
void rb_sys_fail(const char *mesg)
Converts a C errno into a Ruby exception, then raises it.
Definition: error.c:3272
VALUE rb_eRangeError
RangeError exception.
Definition: error.c:1095
VALUE rb_eTypeError
TypeError exception.
Definition: error.c:1091
VALUE rb_eRuntimeError
RuntimeError exception.
Definition: error.c:1089
VALUE rb_exc_new_str(VALUE etype, VALUE str)
Identical to rb_exc_new_cstr(), except it takes a Ruby's string instead of C's.
Definition: error.c:1142
VALUE rb_eArgError
ArgumentError exception.
Definition: error.c:1092
VALUE rb_rescue(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*r_proc)(VALUE, VALUE), VALUE data2)
Identical to rb_rescue2(), except it does not take a list of exception classes.
Definition: eval.c:964
void rb_warning(const char *fmt,...)
Issues a warning.
Definition: error.c:442
VALUE rb_cTime
Time class.
Definition: time.c:672
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition: object.c:3528
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
Definition: object.c:3028
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition: object.c:1980
VALUE rb_Integer(VALUE val)
This is the logic behind Kernel#Integer.
Definition: object.c:3097
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition: object.c:190
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition: object.c:122
VALUE rb_mComparable
Comparable module.
Definition: compar.c:19
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition: object.c:3022
Encoding relates APIs.
Defines RBIMPL_HAS_BUILTIN.
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition: bignum.h:546
#define INTEGER_PACK_LITTLE_ENDIAN
Little endian combination.
Definition: bignum.h:567
#define rb_check_frozen
Just another name of rb_check_frozen.
Definition: error.h:264
void rb_num_zerodiv(void)
Just always raises an exception.
Definition: numeric.c:200
VALUE rb_int_positive_pow(long x, unsigned long y)
Raises the passed x to the power of y.
Definition: numeric.c:4492
VALUE rb_rational_new(VALUE num, VALUE den)
Constructs a Rational, with reduction.
Definition: rational.c:1969
#define rb_Rational1(x)
Shorthand of (x/1)r.
Definition: rational.h:116
VALUE rb_str_subseq(VALUE str, long beg, long len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition: string.c:2825
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition: string.h:1498
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition: string.h:1532
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition: string.c:1834
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition: string.c:3149
#define rb_usascii_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "US ASCII" encoding.
Definition: string.h:1567
VALUE rb_str_concat(VALUE dst, VALUE src)
Identical to rb_str_append(), except it also accepts an integer as a codepoint.
Definition: string.c:3423
#define rb_strlen_lit(str)
Length of a string literal.
Definition: string.h:1692
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition: string.c:2639
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition: string.h:1656
VALUE rb_str_resize(VALUE str, long len)
Overwrites the length of the string.
Definition: string.c:3036
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition: string.h:1514
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition: string.c:1682
VALUE rb_struct_define_under(VALUE space, const char *name,...)
Identical to rb_struct_define(), except it defines the class under the specified namespace instead of...
Definition: struct.c:504
VALUE rb_time_nano_new(time_t sec, long nsec)
Identical to rb_time_new(), except it accepts the time in nanoseconds resolution.
Definition: time.c:2692
void rb_timespec_now(struct timespec *ts)
Fills the current time into the given struct.
Definition: time.c:1933
VALUE rb_time_timespec_new(const struct timespec *ts, int offset)
Creates an instance of rb_cTime, with given time and offset.
Definition: time.c:2698
struct timespec rb_time_timespec(VALUE time)
Identical to rb_time_timeval(), except for return type.
Definition: time.c:2861
VALUE rb_time_new(time_t sec, long usec)
Creates an instance of rb_cTime with the given time and the local timezone.
Definition: time.c:2684
struct timeval rb_time_timeval(VALUE time)
Converts an instance of rb_cTime to a struct timeval that represents the identical point of time.
Definition: time.c:2844
struct timeval rb_time_interval(VALUE num)
Creates a "time interval".
Definition: time.c:2838
VALUE rb_time_num_new(VALUE timev, VALUE off)
Identical to rb_time_timespec_new(), except it takes Ruby values instead of C structs.
Definition: time.c:2721
VALUE rb_time_utc_offset(VALUE time)
Queries the offset, in seconds between the time zone of the time and the UTC.
Definition: time.c:4975
struct timespec rb_time_timespec_interval(VALUE num)
Identical to rb_time_interval(), except for return type.
Definition: time.c:2875
VALUE rb_ivar_set(VALUE obj, ID name, VALUE val)
Identical to rb_iv_set(), except it accepts the name as an ID instead of a C string.
Definition: variable.c:1593
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition: vm_method.c:2823
void rb_alias(VALUE klass, ID dst, ID src)
Resembles alias.
Definition: vm_method.c:2158
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition: vm_eval.c:665
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
VALUE rb_sprintf(const char *fmt,...)
Ruby's extended sprintf(3).
Definition: sprintf.c:1219
VALUE rb_str_catf(VALUE dst, const char *fmt,...)
Identical to rb_sprintf(), except it renders the output to the specified object rather than creating ...
Definition: sprintf.c:1242
#define rb_long2int
Just another name of rb_long2int_inline.
Definition: long.h:62
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
Definition: memory.h:366
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition: memory.h:161
void rb_define_hooked_variable(const char *q, VALUE *w, type *e, void_type *r)
Define a function-backended global variable.
Definition: cxxanyargs.hpp:136
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition: variable.c:1727
#define RARRAY_LEN
Just another name of rb_array_len.
Definition: rarray.h:68
#define RARRAY_AREF(a, i)
Definition: rarray.h:583
#define DATA_PTR(obj)
Convenient getter macro.
Definition: rdata.h:71
#define StringValue(v)
Ensures that the parameter object is a String.
Definition: rstring.h:72
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition: rstring.h:82
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition: rstring.h:95
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition: rtypeddata.h:79
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition: rtypeddata.h:507
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition: rtypeddata.h:489
#define RTEST
This is an old name of RB_TEST.
Definition: timev.h:21
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition: value.h:63
uintptr_t VALUE
Type that represents a Ruby object.
Definition: value.h:40
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition: value.h:52
static bool rb_integer_type_p(VALUE obj)
Queries if the object is an instance of rb_cInteger.
Definition: value_type.h:203