Ruby 3.2.4p170 (2024-04-23 revision af471c0e0127eea0cafa6f308c0425bbfab0acf5)
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
1765 wideval_t timew; /* time_t value * TIME_SCALE. possibly Rational. */
1766 struct vtm vtm;
1767};
1768
1769#define GetTimeval(obj, tobj) ((tobj) = get_timeval(obj))
1770#define GetNewTimeval(obj, tobj) ((tobj) = get_new_timeval(obj))
1771
1772#define IsTimeval(obj) rb_typeddata_is_kind_of((obj), &time_data_type)
1773#define TIME_INIT_P(tobj) ((tobj)->vtm.tzmode != TIME_TZMODE_UNINITIALIZED)
1774
1775#define TZMODE_UTC_P(tobj) ((tobj)->vtm.tzmode == TIME_TZMODE_UTC)
1776#define TZMODE_SET_UTC(tobj) ((tobj)->vtm.tzmode = TIME_TZMODE_UTC)
1777
1778#define TZMODE_LOCALTIME_P(tobj) ((tobj)->vtm.tzmode == TIME_TZMODE_LOCALTIME)
1779#define TZMODE_SET_LOCALTIME(tobj) ((tobj)->vtm.tzmode = TIME_TZMODE_LOCALTIME)
1780
1781#define TZMODE_FIXOFF_P(tobj) ((tobj)->vtm.tzmode == TIME_TZMODE_FIXOFF)
1782#define TZMODE_SET_FIXOFF(tobj, off) \
1783 ((tobj)->vtm.tzmode = TIME_TZMODE_FIXOFF, \
1784 (tobj)->vtm.utc_offset = (off))
1785
1786#define TZMODE_COPY(tobj1, tobj2) \
1787 ((tobj1)->vtm.tzmode = (tobj2)->vtm.tzmode, \
1788 (tobj1)->vtm.utc_offset = (tobj2)->vtm.utc_offset, \
1789 (tobj1)->vtm.zone = (tobj2)->vtm.zone)
1790
1791static int zone_localtime(VALUE zone, VALUE time);
1792static VALUE time_get_tm(VALUE, struct time_object *);
1793#define MAKE_TM(time, tobj) \
1794 do { \
1795 if ((tobj)->vtm.tm_got == 0) { \
1796 time_get_tm((time), (tobj)); \
1797 } \
1798 } while (0)
1799#define MAKE_TM_ENSURE(time, tobj, cond) \
1800 do { \
1801 MAKE_TM(time, tobj); \
1802 if (!(cond)) { \
1803 force_make_tm(time, tobj); \
1804 } \
1805 } while (0)
1806
1807static inline void
1808force_make_tm(VALUE time, struct time_object *tobj)
1809{
1810 VALUE zone = tobj->vtm.zone;
1811 if (!NIL_P(zone) && zone != str_empty && zone != str_utc) {
1812 if (zone_localtime(zone, time)) return;
1813 }
1814 tobj->vtm.tm_got = 0;
1815 time_get_tm(time, tobj);
1816}
1817
1818static void
1819time_mark(void *ptr)
1820{
1821 struct time_object *tobj = ptr;
1822 if (!FIXWV_P(tobj->timew))
1823 rb_gc_mark(w2v(tobj->timew));
1824 rb_gc_mark(tobj->vtm.year);
1825 rb_gc_mark(tobj->vtm.subsecx);
1826 rb_gc_mark(tobj->vtm.utc_offset);
1827 rb_gc_mark(tobj->vtm.zone);
1828}
1829
1830static size_t
1831time_memsize(const void *tobj)
1832{
1833 return sizeof(struct time_object);
1834}
1835
1836static const rb_data_type_t time_data_type = {
1837 "time",
1838 {time_mark, RUBY_TYPED_DEFAULT_FREE, time_memsize,},
1839 0, 0,
1840 (RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE),
1841};
1842
1843static VALUE
1844time_s_alloc(VALUE klass)
1845{
1846 VALUE obj;
1847 struct time_object *tobj;
1848
1849 obj = TypedData_Make_Struct(klass, struct time_object, &time_data_type, tobj);
1850 tobj->vtm.tzmode = TIME_TZMODE_UNINITIALIZED;
1851 tobj->vtm.tm_got = 0;
1852 tobj->timew = WINT2FIXWV(0);
1853 tobj->vtm.zone = Qnil;
1854
1855 return obj;
1856}
1857
1858static struct time_object *
1859get_timeval(VALUE obj)
1860{
1861 struct time_object *tobj;
1862 TypedData_Get_Struct(obj, struct time_object, &time_data_type, tobj);
1863 if (!TIME_INIT_P(tobj)) {
1864 rb_raise(rb_eTypeError, "uninitialized %"PRIsVALUE, rb_obj_class(obj));
1865 }
1866 return tobj;
1867}
1868
1869static struct time_object *
1870get_new_timeval(VALUE obj)
1871{
1872 struct time_object *tobj;
1873 TypedData_Get_Struct(obj, struct time_object, &time_data_type, tobj);
1874 if (TIME_INIT_P(tobj)) {
1875 rb_raise(rb_eTypeError, "already initialized %"PRIsVALUE, rb_obj_class(obj));
1876 }
1877 return tobj;
1878}
1879
1880static void
1881time_modify(VALUE time)
1882{
1883 rb_check_frozen(time);
1884}
1885
1886static wideval_t
1887timenano2timew(time_t sec, long nsec)
1888{
1889 wideval_t timew;
1890
1891 timew = rb_time_magnify(TIMET2WV(sec));
1892 if (nsec)
1893 timew = wadd(timew, wmulquoll(WINT2WV(nsec), TIME_SCALE, 1000000000));
1894 return timew;
1895}
1896
1897static struct timespec
1898timew2timespec(wideval_t timew)
1899{
1900 VALUE subsecx;
1901 struct timespec ts;
1902 wideval_t timew2;
1903
1904 if (timew_out_of_timet_range(timew))
1905 rb_raise(rb_eArgError, "time out of system range");
1906 split_second(timew, &timew2, &subsecx);
1907 ts.tv_sec = WV2TIMET(timew2);
1908 ts.tv_nsec = NUM2LONG(mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE)));
1909 return ts;
1910}
1911
1912static struct timespec *
1913timew2timespec_exact(wideval_t timew, struct timespec *ts)
1914{
1915 VALUE subsecx;
1916 wideval_t timew2;
1917 VALUE nsecv;
1918
1919 if (timew_out_of_timet_range(timew))
1920 return NULL;
1921 split_second(timew, &timew2, &subsecx);
1922 ts->tv_sec = WV2TIMET(timew2);
1923 nsecv = mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE));
1924 if (!FIXNUM_P(nsecv))
1925 return NULL;
1926 ts->tv_nsec = NUM2LONG(nsecv);
1927 return ts;
1928}
1929
1930void
1932{
1933#ifdef HAVE_CLOCK_GETTIME
1934 if (clock_gettime(CLOCK_REALTIME, ts) == -1) {
1935 rb_sys_fail("clock_gettime");
1936 }
1937#else
1938 {
1939 struct timeval tv;
1940 if (gettimeofday(&tv, 0) < 0) {
1941 rb_sys_fail("gettimeofday");
1942 }
1943 ts->tv_sec = tv.tv_sec;
1944 ts->tv_nsec = tv.tv_usec * 1000;
1945 }
1946#endif
1947}
1948
1949static VALUE
1950time_init_now(rb_execution_context_t *ec, VALUE time, VALUE zone)
1951{
1952 struct time_object *tobj;
1953 struct timespec ts;
1954
1955 time_modify(time);
1956 GetNewTimeval(time, tobj);
1957 TZMODE_SET_LOCALTIME(tobj);
1958 tobj->vtm.tm_got=0;
1959 tobj->timew = WINT2FIXWV(0);
1960 rb_timespec_now(&ts);
1961 tobj->timew = timenano2timew(ts.tv_sec, ts.tv_nsec);
1962
1963 if (!NIL_P(zone)) {
1964 time_zonelocal(time, zone);
1965 }
1966 return time;
1967}
1968
1969static VALUE
1970time_s_now(rb_execution_context_t *ec, VALUE klass, VALUE zone)
1971{
1972 VALUE t = time_s_alloc(klass);
1973 return time_init_now(ec, t, zone);
1974}
1975
1976static VALUE
1977time_set_utc_offset(VALUE time, VALUE off)
1978{
1979 struct time_object *tobj;
1980 off = num_exact(off);
1981
1982 time_modify(time);
1983 GetTimeval(time, tobj);
1984
1985 tobj->vtm.tm_got = 0;
1986 tobj->vtm.zone = Qnil;
1987 TZMODE_SET_FIXOFF(tobj, off);
1988
1989 return time;
1990}
1991
1992static void
1993vtm_add_offset(struct vtm *vtm, VALUE off, int sign)
1994{
1995 VALUE subsec, v;
1996 int sec, min, hour;
1997 int day;
1998
1999 if (lt(off, INT2FIX(0))) {
2000 sign = -sign;
2001 off = neg(off);
2002 }
2003 divmodv(off, INT2FIX(1), &off, &subsec);
2004 divmodv(off, INT2FIX(60), &off, &v);
2005 sec = NUM2INT(v);
2006 divmodv(off, INT2FIX(60), &off, &v);
2007 min = NUM2INT(v);
2008 divmodv(off, INT2FIX(24), &off, &v);
2009 hour = NUM2INT(v);
2010
2011 if (sign < 0) {
2012 subsec = neg(subsec);
2013 sec = -sec;
2014 min = -min;
2015 hour = -hour;
2016 }
2017
2018 day = 0;
2019
2020 if (!rb_equal(subsec, INT2FIX(0))) {
2021 vtm->subsecx = addv(vtm->subsecx, w2v(rb_time_magnify(v2w(subsec))));
2022 if (lt(vtm->subsecx, INT2FIX(0))) {
2023 vtm->subsecx = addv(vtm->subsecx, INT2FIX(TIME_SCALE));
2024 sec -= 1;
2025 }
2026 if (le(INT2FIX(TIME_SCALE), vtm->subsecx)) {
2027 vtm->subsecx = subv(vtm->subsecx, INT2FIX(TIME_SCALE));
2028 sec += 1;
2029 }
2030 }
2031 if (sec) {
2032 /* If sec + subsec == 0, don't change vtm->sec.
2033 * It may be 60 which is a leap second. */
2034 sec += vtm->sec;
2035 if (sec < 0) {
2036 sec += 60;
2037 min -= 1;
2038 }
2039 if (60 <= sec) {
2040 sec -= 60;
2041 min += 1;
2042 }
2043 vtm->sec = sec;
2044 }
2045 if (min) {
2046 min += vtm->min;
2047 if (min < 0) {
2048 min += 60;
2049 hour -= 1;
2050 }
2051 if (60 <= min) {
2052 min -= 60;
2053 hour += 1;
2054 }
2055 vtm->min = min;
2056 }
2057 if (hour) {
2058 hour += vtm->hour;
2059 if (hour < 0) {
2060 hour += 24;
2061 day = -1;
2062 }
2063 if (24 <= hour) {
2064 hour -= 24;
2065 day = 1;
2066 }
2067 vtm->hour = hour;
2068 }
2069
2070 vtm_add_day(vtm, day);
2071}
2072
2073static void
2074vtm_add_day(struct vtm *vtm, int day)
2075{
2076 if (day) {
2077 if (day < 0) {
2078 if (vtm->mon == 1 && vtm->mday == 1) {
2079 vtm->mday = 31;
2080 vtm->mon = 12; /* December */
2081 vtm->year = subv(vtm->year, INT2FIX(1));
2082 if (vtm->yday != 0)
2083 vtm->yday = leap_year_v_p(vtm->year) ? 366 : 365;
2084 }
2085 else if (vtm->mday == 1) {
2086 const int8_t *days_in_month = days_in_month_in_v(vtm->year);
2087 vtm->mon--;
2088 vtm->mday = days_in_month[vtm->mon-1];
2089 if (vtm->yday != 0) vtm->yday--;
2090 }
2091 else {
2092 vtm->mday--;
2093 if (vtm->yday != 0) vtm->yday--;
2094 }
2095 if (vtm->wday != VTM_WDAY_INITVAL) vtm->wday = (vtm->wday + 6) % 7;
2096 }
2097 else {
2098 int leap = leap_year_v_p(vtm->year);
2099 if (vtm->mon == 12 && vtm->mday == 31) {
2100 vtm->year = addv(vtm->year, INT2FIX(1));
2101 vtm->mon = 1; /* January */
2102 vtm->mday = 1;
2103 vtm->yday = 1;
2104 }
2105 else if (vtm->mday == days_in_month_of(leap)[vtm->mon-1]) {
2106 vtm->mon++;
2107 vtm->mday = 1;
2108 if (vtm->yday != 0) vtm->yday++;
2109 }
2110 else {
2111 vtm->mday++;
2112 if (vtm->yday != 0) vtm->yday++;
2113 }
2114 if (vtm->wday != VTM_WDAY_INITVAL) vtm->wday = (vtm->wday + 1) % 7;
2115 }
2116 }
2117}
2118
2119static int
2120maybe_tzobj_p(VALUE obj)
2121{
2122 if (NIL_P(obj)) return FALSE;
2123 if (RB_INTEGER_TYPE_P(obj)) return FALSE;
2124 if (RB_TYPE_P(obj, T_STRING)) return FALSE;
2125 return TRUE;
2126}
2127
2128NORETURN(static void invalid_utc_offset(VALUE));
2129static void
2130invalid_utc_offset(VALUE zone)
2131{
2132 rb_raise(rb_eArgError, "\"+HH:MM\", \"-HH:MM\", \"UTC\" or "
2133 "\"A\"..\"I\",\"K\"..\"Z\" expected for utc_offset: %"PRIsVALUE,
2134 zone);
2135}
2136
2137static VALUE
2138utc_offset_arg(VALUE arg)
2139{
2140 VALUE tmp;
2141 if (!NIL_P(tmp = rb_check_string_type(arg))) {
2142 int n = 0;
2143 const char *s = RSTRING_PTR(tmp), *min = NULL, *sec = NULL;
2144 if (!rb_enc_str_asciicompat_p(tmp)) {
2145 goto invalid_utc_offset;
2146 }
2147 switch (RSTRING_LEN(tmp)) {
2148 case 1:
2149 if (s[0] == 'Z') {
2150 return UTC_ZONE;
2151 }
2152 /* Military Time Zone Names */
2153 if (s[0] >= 'A' && s[0] <= 'I') {
2154 n = (int)s[0] - 'A' + 1;
2155 }
2156 /* No 'J' zone */
2157 else if (s[0] >= 'K' && s[0] <= 'M') {
2158 n = (int)s[0] - 'A';
2159 }
2160 else if (s[0] >= 'N' && s[0] <= 'Y') {
2161 n = 'M' - (int)s[0];
2162 }
2163 else {
2164 goto invalid_utc_offset;
2165 }
2166 n *= 3600;
2167 return INT2FIX(n);
2168 case 3:
2169 if (STRNCASECMP("UTC", s, 3) == 0) {
2170 return UTC_ZONE;
2171 }
2172 break; /* +HH */
2173 case 7: /* +HHMMSS */
2174 sec = s+5;
2175 /* fallthrough */
2176 case 5: /* +HHMM */
2177 min = s+3;
2178 break;
2179 case 9: /* +HH:MM:SS */
2180 if (s[6] != ':') goto invalid_utc_offset;
2181 sec = s+7;
2182 /* fallthrough */
2183 case 6: /* +HH:MM */
2184 if (s[3] != ':') goto invalid_utc_offset;
2185 min = s+4;
2186 break;
2187 default:
2188 goto invalid_utc_offset;
2189 }
2190 if (sec) {
2191 if (!ISDIGIT(sec[0]) || !ISDIGIT(sec[1])) goto invalid_utc_offset;
2192 n += (sec[0] * 10 + sec[1] - '0' * 11);
2193 ASSUME(min);
2194 }
2195 if (min) {
2196 if (!ISDIGIT(min[0]) || !ISDIGIT(min[1])) goto invalid_utc_offset;
2197 if (min[0] > '5') goto invalid_utc_offset;
2198 n += (min[0] * 10 + min[1] - '0' * 11) * 60;
2199 }
2200 if (s[0] != '+' && s[0] != '-') goto invalid_utc_offset;
2201 if (!ISDIGIT(s[1]) || !ISDIGIT(s[2])) goto invalid_utc_offset;
2202 n += (s[1] * 10 + s[2] - '0' * 11) * 3600;
2203 if (s[0] == '-') {
2204 if (n == 0) return UTC_ZONE;
2205 n = -n;
2206 }
2207 return INT2FIX(n);
2208 }
2209 else {
2210 return num_exact(arg);
2211 }
2212 invalid_utc_offset:
2213 return Qnil;
2214}
2215
2216static void
2217zone_set_offset(VALUE zone, struct time_object *tobj,
2218 wideval_t tlocal, wideval_t tutc)
2219{
2220 /* tlocal and tutc must be unmagnified and in seconds */
2221 wideval_t w = wsub(tlocal, tutc);
2222 VALUE off = w2v(w);
2223 validate_utc_offset(off);
2224 tobj->vtm.utc_offset = off;
2225 tobj->vtm.zone = zone;
2226 TZMODE_SET_LOCALTIME(tobj);
2227}
2228
2229static wideval_t
2230extract_time(VALUE time)
2231{
2232 wideval_t t;
2233 const ID id_to_i = idTo_i;
2234
2235#define EXTRACT_TIME() do { \
2236 t = v2w(rb_Integer(AREF(to_i))); \
2237 } while (0)
2238
2239 if (rb_typeddata_is_kind_of(time, &time_data_type)) {
2240 struct time_object *tobj = DATA_PTR(time);
2241
2242 time_gmtime(time); /* ensure tm got */
2243 t = rb_time_unmagnify(tobj->timew);
2244 }
2245 else if (RB_TYPE_P(time, T_STRUCT)) {
2246#define AREF(x) rb_struct_aref(time, ID2SYM(id_##x))
2247 EXTRACT_TIME();
2248#undef AREF
2249 }
2250 else {
2251#define AREF(x) rb_funcallv(time, id_##x, 0, 0)
2252 EXTRACT_TIME();
2253#undef AREF
2254 }
2255#undef EXTRACT_TIME
2256
2257 return t;
2258}
2259
2260static wideval_t
2261extract_vtm(VALUE time, struct vtm *vtm, VALUE subsecx)
2262{
2263 wideval_t t;
2264 const ID id_to_i = idTo_i;
2265
2266#define EXTRACT_VTM() do { \
2267 VALUE subsecx; \
2268 vtm->year = obj2vint(AREF(year)); \
2269 vtm->mon = month_arg(AREF(mon)); \
2270 vtm->mday = obj2ubits(AREF(mday), 5); \
2271 vtm->hour = obj2ubits(AREF(hour), 5); \
2272 vtm->min = obj2ubits(AREF(min), 6); \
2273 vtm->sec = obj2subsecx(AREF(sec), &subsecx); \
2274 vtm->isdst = RTEST(AREF(isdst)); \
2275 vtm->utc_offset = Qnil; \
2276 t = v2w(rb_Integer(AREF(to_i))); \
2277 } while (0)
2278
2279 if (rb_typeddata_is_kind_of(time, &time_data_type)) {
2280 struct time_object *tobj = DATA_PTR(time);
2281
2282 time_get_tm(time, tobj);
2283 *vtm = tobj->vtm;
2284 t = rb_time_unmagnify(tobj->timew);
2285 if (TZMODE_FIXOFF_P(tobj) && vtm->utc_offset != INT2FIX(0))
2286 t = wadd(t, v2w(vtm->utc_offset));
2287 }
2288 else if (RB_TYPE_P(time, T_STRUCT)) {
2289#define AREF(x) rb_struct_aref(time, ID2SYM(id_##x))
2290 EXTRACT_VTM();
2291#undef AREF
2292 }
2293 else if (rb_integer_type_p(time)) {
2294 t = v2w(time);
2295 GMTIMEW(rb_time_magnify(t), vtm);
2296 }
2297 else {
2298#define AREF(x) rb_funcallv(time, id_##x, 0, 0)
2299 EXTRACT_VTM();
2300#undef AREF
2301 }
2302#undef EXTRACT_VTM
2303 vtm->subsecx = subsecx;
2304 validate_vtm(vtm);
2305 return t;
2306}
2307
2308static void
2309zone_set_dst(VALUE zone, struct time_object *tobj, VALUE tm)
2310{
2311 ID id_dst_p;
2312 VALUE dst;
2313 CONST_ID(id_dst_p, "dst?");
2314 dst = rb_check_funcall(zone, id_dst_p, 1, &tm);
2315 tobj->vtm.isdst = (!UNDEF_P(dst) && RTEST(dst));
2316}
2317
2318static int
2319zone_timelocal(VALUE zone, VALUE time)
2320{
2321 VALUE utc, tm;
2322 struct time_object *tobj = DATA_PTR(time);
2323 wideval_t t, s;
2324
2325 split_second(tobj->timew, &t, &s);
2326 tm = tm_from_time(rb_cTimeTM, time);
2327 utc = rb_check_funcall(zone, id_local_to_utc, 1, &tm);
2328 if (UNDEF_P(utc)) return 0;
2329
2330 s = extract_time(utc);
2331 zone_set_offset(zone, tobj, t, s);
2332 s = rb_time_magnify(s);
2333 if (tobj->vtm.subsecx != INT2FIX(0)) {
2334 s = wadd(s, v2w(tobj->vtm.subsecx));
2335 }
2336 tobj->timew = s;
2337 zone_set_dst(zone, tobj, tm);
2338 return 1;
2339}
2340
2341static int
2342zone_localtime(VALUE zone, VALUE time)
2343{
2344 VALUE local, tm, subsecx;
2345 struct time_object *tobj = DATA_PTR(time);
2346 wideval_t t, s;
2347
2348 split_second(tobj->timew, &t, &subsecx);
2349 tm = tm_from_time(rb_cTimeTM, time);
2350
2351 local = rb_check_funcall(zone, id_utc_to_local, 1, &tm);
2352 if (UNDEF_P(local)) return 0;
2353
2354 s = extract_vtm(local, &tobj->vtm, subsecx);
2355 tobj->vtm.tm_got = 1;
2356 zone_set_offset(zone, tobj, s, t);
2357 zone_set_dst(zone, tobj, tm);
2358 return 1;
2359}
2360
2361static VALUE
2362find_timezone(VALUE time, VALUE zone)
2363{
2364 VALUE klass = CLASS_OF(time);
2365
2366 return rb_check_funcall_default(klass, id_find_timezone, 1, &zone, Qnil);
2367}
2368
2369/* Turn the special case 24:00:00 of already validated vtm into
2370 * 00:00:00 the next day */
2371static void
2372vtm_day_wraparound(struct vtm *vtm)
2373{
2374 if (vtm->hour < 24) return;
2375
2376 /* Assuming UTC and no care of DST, just reset hour and advance
2377 * date, not to discard the validated vtm. */
2378 vtm->hour = 0;
2379 vtm_add_day(vtm, 1);
2380}
2381
2382static VALUE time_init_vtm(VALUE time, struct vtm vtm, VALUE zone);
2383
2384static VALUE
2385time_init_args(rb_execution_context_t *ec, VALUE time, VALUE year, VALUE mon, VALUE mday,
2386 VALUE hour, VALUE min, VALUE sec, VALUE zone)
2387{
2388 struct vtm vtm;
2389
2390 vtm.wday = VTM_WDAY_INITVAL;
2391 vtm.yday = 0;
2392 vtm.zone = str_empty;
2393
2394 vtm.year = obj2vint(year);
2395
2396 vtm.mon = NIL_P(mon) ? 1 : month_arg(mon);
2397
2398 vtm.mday = NIL_P(mday) ? 1 : obj2ubits(mday, 5);
2399
2400 vtm.hour = NIL_P(hour) ? 0 : obj2ubits(hour, 5);
2401
2402 vtm.min = NIL_P(min) ? 0 : obj2ubits(min, 6);
2403
2404 if (NIL_P(sec)) {
2405 vtm.sec = 0;
2406 vtm.subsecx = INT2FIX(0);
2407 }
2408 else {
2409 VALUE subsecx;
2410 vtm.sec = obj2subsecx(sec, &subsecx);
2411 vtm.subsecx = subsecx;
2412 }
2413
2414 return time_init_vtm(time, vtm, zone);
2415}
2416
2417static VALUE
2418time_init_vtm(VALUE time, struct vtm vtm, VALUE zone)
2419{
2420 VALUE utc = Qnil;
2421 struct time_object *tobj;
2422
2423 vtm.isdst = VTM_ISDST_INITVAL;
2424 vtm.utc_offset = Qnil;
2425 const VALUE arg = zone;
2426 if (!NIL_P(arg)) {
2427 zone = Qnil;
2428 if (arg == ID2SYM(rb_intern("dst")))
2429 vtm.isdst = 1;
2430 else if (arg == ID2SYM(rb_intern("std")))
2431 vtm.isdst = 0;
2432 else if (maybe_tzobj_p(arg))
2433 zone = arg;
2434 else if (!NIL_P(utc = utc_offset_arg(arg)))
2435 vtm.utc_offset = utc == UTC_ZONE ? INT2FIX(0) : utc;
2436 else if (NIL_P(zone = find_timezone(time, arg)))
2437 invalid_utc_offset(arg);
2438 }
2439
2440 validate_vtm(&vtm);
2441
2442 time_modify(time);
2443 GetNewTimeval(time, tobj);
2444
2445 if (!NIL_P(zone)) {
2446 tobj->timew = timegmw(&vtm);
2447 vtm_day_wraparound(&vtm);
2448 tobj->vtm = vtm;
2449 tobj->vtm.tm_got = 1;
2450 TZMODE_SET_LOCALTIME(tobj);
2451 if (zone_timelocal(zone, time)) {
2452 return time;
2453 }
2454 else if (NIL_P(vtm.utc_offset = utc_offset_arg(zone))) {
2455 if (NIL_P(zone = find_timezone(time, zone)) || !zone_timelocal(zone, time))
2456 invalid_utc_offset(arg);
2457 }
2458 }
2459
2460 if (utc == UTC_ZONE) {
2461 tobj->timew = timegmw(&vtm);
2462 vtm.isdst = 0; /* No DST in UTC */
2463 vtm_day_wraparound(&vtm);
2464 tobj->vtm = vtm;
2465 tobj->vtm.tm_got = 1;
2466 TZMODE_SET_UTC(tobj);
2467 return time;
2468 }
2469
2470 TZMODE_SET_LOCALTIME(tobj);
2471 tobj->vtm.tm_got=0;
2472 tobj->timew = WINT2FIXWV(0);
2473
2474 if (!NIL_P(vtm.utc_offset)) {
2475 VALUE off = vtm.utc_offset;
2476 vtm_add_offset(&vtm, off, -1);
2477 vtm.utc_offset = Qnil;
2478 tobj->timew = timegmw(&vtm);
2479 return time_set_utc_offset(time, off);
2480 }
2481 else {
2482 tobj->timew = timelocalw(&vtm);
2483 return time_localtime(time);
2484 }
2485}
2486
2487static int
2488two_digits(const char *ptr, const char *end, const char **endp, const char *name)
2489{
2490 ssize_t len = end - ptr;
2491 if (len < 2 || (!ISDIGIT(ptr[0]) || !ISDIGIT(ptr[1])) ||
2492 ((len > 2) && ISDIGIT(ptr[2]))) {
2493 VALUE mesg = rb_sprintf("two digits %s is expected", name);
2494 if (ptr[-1] == '-' || ptr[-1] == ':') {
2495 rb_str_catf(mesg, " after `%c'", ptr[-1]);
2496 }
2497 rb_str_catf(mesg, ": %.*s", ((len > 10) ? 10 : (int)(end - ptr)) + 1, ptr - 1);
2499 }
2500 *endp = ptr + 2;
2501 return (ptr[0] - '0') * 10 + (ptr[1] - '0');
2502}
2503
2504static VALUE
2505parse_int(const char *ptr, const char *end, const char **endp, size_t *ndigits, bool sign)
2506{
2507 ssize_t len = (end - ptr);
2508 int flags = sign ? RB_INT_PARSE_SIGN : 0;
2509 return rb_int_parse_cstr(ptr, len, (char **)endp, ndigits, 10, flags);
2510}
2511
2512static VALUE
2513time_init_parse(rb_execution_context_t *ec, VALUE klass, VALUE str, VALUE zone, VALUE precision)
2514{
2515 if (NIL_P(str = rb_check_string_type(str))) return Qnil;
2516 if (!rb_enc_str_asciicompat_p(str)) {
2517 rb_raise(rb_eArgError, "time string should have ASCII compatible encoding");
2518 }
2519
2520 const char *const begin = RSTRING_PTR(str);
2521 const char *const end = RSTRING_END(str);
2522 const char *ptr = begin;
2523 VALUE year = Qnil, subsec = Qnil;
2524 int mon = -1, mday = -1, hour = -1, min = -1, sec = -1;
2525 size_t ndigits;
2526 size_t prec = NIL_P(precision) ? SIZE_MAX : NUM2SIZET(precision);
2527
2528 if ((ptr < end) && (ISSPACE(*ptr) || ISSPACE(*(end-1)))) {
2529 rb_raise(rb_eArgError, "can't parse: %+"PRIsVALUE, str);
2530 }
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 else if (ptr == end) {
2539 goto only_year;
2540 }
2541 do {
2542#define peekable_p(n) ((ptrdiff_t)(n) < (end - ptr))
2543#define peek_n(c, n) (peekable_p(n) && ((unsigned char)ptr[n] == (c)))
2544#define peek(c) peek_n(c, 0)
2545#define peekc_n(n) (peekable_p(n) ? (int)(unsigned char)ptr[n] : -1)
2546#define peekc() peekc_n(0)
2547#define expect_two_digits(x, bits) \
2548 (((unsigned int)(x = two_digits(ptr + 1, end, &ptr, #x)) > (1U << bits) - 1) ? \
2549 rb_raise(rb_eArgError, #x" out of range") : (void)0)
2550 if (!peek('-')) break;
2551 expect_two_digits(mon, 4);
2552 if (!peek('-')) break;
2553 expect_two_digits(mday, 5);
2554 if (!peek(' ') && !peek('T')) break;
2555 const char *const time_part = ptr + 1;
2556 if (!ISDIGIT(peekc_n(1))) break;
2557#define nofraction(x) \
2558 if (peek('.')) { \
2559 rb_raise(rb_eArgError, "fraction " #x " is not supported: %.*s", \
2560 (int)(ptr + 1 - time_part), time_part); \
2561 }
2562#define need_colon(x) \
2563 if (!peek(':')) { \
2564 rb_raise(rb_eArgError, "missing " #x " part: %.*s", \
2565 (int)(ptr + 1 - time_part), time_part); \
2566 }
2567 expect_two_digits(hour, 5);
2568 nofraction(hour);
2569 need_colon(min);
2570 expect_two_digits(min, 6);
2571 nofraction(min);
2572 need_colon(sec);
2573 expect_two_digits(sec, 6);
2574 if (peek('.')) {
2575 ptr++;
2576 for (ndigits = 0; ndigits < prec && ISDIGIT(peekc_n(ndigits)); ++ndigits);
2577 if (!ndigits) {
2578 int clen = rb_enc_precise_mbclen(ptr, end, rb_enc_get(str));
2579 if (clen < 0) clen = 0;
2580 rb_raise(rb_eArgError, "subsecond expected after dot: %.*s",
2581 (int)(ptr - time_part) + clen, time_part);
2582 }
2583 subsec = parse_int(ptr, ptr + ndigits, &ptr, &ndigits, false);
2584 if (NIL_P(subsec)) break;
2585 while (ptr < end && ISDIGIT(*ptr)) ptr++;
2586 }
2587 } while (0);
2588 while (ptr < end && ISSPACE(*ptr)) ptr++;
2589 const char *const zstr = ptr;
2590 while (ptr < end && !ISSPACE(*ptr)) ptr++;
2591 const char *const zend = ptr;
2592 while (ptr < end && ISSPACE(*ptr)) ptr++;
2593 if (ptr < end) {
2594 VALUE mesg = rb_str_new_cstr("can't parse at: ");
2595 rb_str_cat(mesg, ptr, end - ptr);
2597 }
2598 if (zend > zstr) {
2599 zone = rb_str_subseq(str, zstr - begin, zend - zstr);
2600 }
2601 else if (hour == -1) {
2602 rb_raise(rb_eArgError, "no time information");
2603 }
2604 if (!NIL_P(subsec)) {
2605 /* subseconds is the last using ndigits */
2606 static const size_t TIME_SCALE_NUMDIGITS =
2607 /* TIME_SCALE should be 10000... */
2608 rb_strlen_lit(STRINGIZE(TIME_SCALE)) - 1;
2609
2610 if (ndigits < TIME_SCALE_NUMDIGITS) {
2611 VALUE mul = rb_int_positive_pow(10, TIME_SCALE_NUMDIGITS - ndigits);
2612 subsec = rb_int_mul(subsec, mul);
2613 }
2614 else if (ndigits > TIME_SCALE_NUMDIGITS) {
2615 VALUE num = rb_int_positive_pow(10, ndigits - TIME_SCALE_NUMDIGITS);
2616 subsec = rb_rational_new(subsec, num);
2617 }
2618 }
2619
2620only_year:
2621 ;
2622
2623 struct vtm vtm = {
2624 .wday = VTM_WDAY_INITVAL,
2625 .yday = 0,
2626 .zone = str_empty,
2627 .year = year,
2628 .mon = (mon < 0) ? 1 : mon,
2629 .mday = (mday < 0) ? 1 : mday,
2630 .hour = (hour < 0) ? 0 : hour,
2631 .min = (min < 0) ? 0 : min,
2632 .sec = (sec < 0) ? 0 : sec,
2633 .subsecx = NIL_P(subsec) ? INT2FIX(0) : subsec,
2634 };
2635 return time_init_vtm(klass, vtm, zone);
2636}
2637
2638static void
2639subsec_normalize(time_t *secp, long *subsecp, const long maxsubsec)
2640{
2641 time_t sec = *secp;
2642 long subsec = *subsecp;
2643 long sec2;
2644
2645 if (UNLIKELY(subsec >= maxsubsec)) { /* subsec positive overflow */
2646 sec2 = subsec / maxsubsec;
2647 if (TIMET_MAX - sec2 < sec) {
2648 rb_raise(rb_eRangeError, "out of Time range");
2649 }
2650 subsec -= sec2 * maxsubsec;
2651 sec += sec2;
2652 }
2653 else if (UNLIKELY(subsec < 0)) { /* subsec negative overflow */
2654 sec2 = NDIV(subsec, maxsubsec); /* negative div */
2655 if (sec < TIMET_MIN - sec2) {
2656 rb_raise(rb_eRangeError, "out of Time range");
2657 }
2658 subsec -= sec2 * maxsubsec;
2659 sec += sec2;
2660 }
2661#ifndef NEGATIVE_TIME_T
2662 if (sec < 0)
2663 rb_raise(rb_eArgError, "time must be positive");
2664#endif
2665 *secp = sec;
2666 *subsecp = subsec;
2667}
2668
2669#define time_usec_normalize(secp, usecp) subsec_normalize(secp, usecp, 1000000)
2670#define time_nsec_normalize(secp, nsecp) subsec_normalize(secp, nsecp, 1000000000)
2671
2672static wideval_t
2673nsec2timew(time_t sec, long nsec)
2674{
2675 time_nsec_normalize(&sec, &nsec);
2676 return timenano2timew(sec, nsec);
2677}
2678
2679static VALUE
2680time_new_timew(VALUE klass, wideval_t timew)
2681{
2682 VALUE time = time_s_alloc(klass);
2683 struct time_object *tobj;
2684
2685 tobj = DATA_PTR(time); /* skip type check */
2686 TZMODE_SET_LOCALTIME(tobj);
2687 tobj->timew = timew;
2688
2689 return time;
2690}
2691
2692VALUE
2693rb_time_new(time_t sec, long usec)
2694{
2695 time_usec_normalize(&sec, &usec);
2696 return time_new_timew(rb_cTime, timenano2timew(sec, usec * 1000));
2697}
2698
2699/* returns localtime time object */
2700VALUE
2701rb_time_nano_new(time_t sec, long nsec)
2702{
2703 return time_new_timew(rb_cTime, nsec2timew(sec, nsec));
2704}
2705
2706VALUE
2707rb_time_timespec_new(const struct timespec *ts, int offset)
2708{
2709 struct time_object *tobj;
2710 VALUE time = time_new_timew(rb_cTime, nsec2timew(ts->tv_sec, ts->tv_nsec));
2711
2712 if (-86400 < offset && offset < 86400) { /* fixoff */
2713 GetTimeval(time, tobj);
2714 TZMODE_SET_FIXOFF(tobj, INT2FIX(offset));
2715 }
2716 else if (offset == INT_MAX) { /* localtime */
2717 }
2718 else if (offset == INT_MAX-1) { /* UTC */
2719 GetTimeval(time, tobj);
2720 TZMODE_SET_UTC(tobj);
2721 }
2722 else {
2723 rb_raise(rb_eArgError, "utc_offset out of range");
2724 }
2725
2726 return time;
2727}
2728
2729VALUE
2731{
2732 VALUE time = time_new_timew(rb_cTime, rb_time_magnify(v2w(timev)));
2733
2734 if (!NIL_P(off)) {
2735 VALUE zone = off;
2736
2737 if (maybe_tzobj_p(zone)) {
2738 time_gmtime(time);
2739 if (zone_timelocal(zone, time)) return time;
2740 }
2741 if (NIL_P(off = utc_offset_arg(off))) {
2742 off = zone;
2743 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
2744 time_gmtime(time);
2745 if (!zone_timelocal(zone, time)) invalid_utc_offset(off);
2746 return time;
2747 }
2748 else if (off == UTC_ZONE) {
2749 return time_gmtime(time);
2750 }
2751
2752 validate_utc_offset(off);
2753 time_set_utc_offset(time, off);
2754 return time;
2755 }
2756
2757 return time;
2758}
2759
2760static struct timespec
2761time_timespec(VALUE num, int interval)
2762{
2763 struct timespec t;
2764 const char *const tstr = interval ? "time interval" : "time";
2765 VALUE i, f, ary;
2766
2767#ifndef NEGATIVE_TIME_T
2768# define arg_range_check(v) \
2769 (((v) < 0) ? \
2770 rb_raise(rb_eArgError, "%s must not be negative", tstr) : \
2771 (void)0)
2772#else
2773# define arg_range_check(v) \
2774 ((interval && (v) < 0) ? \
2775 rb_raise(rb_eArgError, "time interval must not be negative") : \
2776 (void)0)
2777#endif
2778
2779 if (FIXNUM_P(num)) {
2780 t.tv_sec = NUM2TIMET(num);
2781 arg_range_check(t.tv_sec);
2782 t.tv_nsec = 0;
2783 }
2784 else if (RB_FLOAT_TYPE_P(num)) {
2785 double x = RFLOAT_VALUE(num);
2786 arg_range_check(x);
2787 {
2788 double f, d;
2789
2790 d = modf(x, &f);
2791 if (d >= 0) {
2792 t.tv_nsec = (int)(d*1e9+0.5);
2793 if (t.tv_nsec >= 1000000000) {
2794 t.tv_nsec -= 1000000000;
2795 f += 1;
2796 }
2797 }
2798 else if ((t.tv_nsec = (int)(-d*1e9+0.5)) > 0) {
2799 t.tv_nsec = 1000000000 - t.tv_nsec;
2800 f -= 1;
2801 }
2802 t.tv_sec = (time_t)f;
2803 if (f != t.tv_sec) {
2804 rb_raise(rb_eRangeError, "%f out of Time range", x);
2805 }
2806 }
2807 }
2808 else if (RB_BIGNUM_TYPE_P(num)) {
2809 t.tv_sec = NUM2TIMET(num);
2810 arg_range_check(t.tv_sec);
2811 t.tv_nsec = 0;
2812 }
2813 else {
2814 i = INT2FIX(1);
2815 ary = rb_check_funcall(num, id_divmod, 1, &i);
2816 if (!UNDEF_P(ary) && !NIL_P(ary = rb_check_array_type(ary))) {
2817 i = rb_ary_entry(ary, 0);
2818 f = rb_ary_entry(ary, 1);
2819 t.tv_sec = NUM2TIMET(i);
2820 arg_range_check(t.tv_sec);
2821 f = rb_funcall(f, '*', 1, INT2FIX(1000000000));
2822 t.tv_nsec = NUM2LONG(f);
2823 }
2824 else {
2825 rb_raise(rb_eTypeError, "can't convert %"PRIsVALUE" into %s",
2826 rb_obj_class(num), tstr);
2827 }
2828 }
2829 return t;
2830#undef arg_range_check
2831}
2832
2833static struct timeval
2834time_timeval(VALUE num, int interval)
2835{
2836 struct timespec ts;
2837 struct timeval tv;
2838
2839 ts = time_timespec(num, interval);
2840 tv.tv_sec = (TYPEOF_TIMEVAL_TV_SEC)ts.tv_sec;
2841 tv.tv_usec = (TYPEOF_TIMEVAL_TV_USEC)(ts.tv_nsec / 1000);
2842
2843 return tv;
2844}
2845
2846struct timeval
2848{
2849 return time_timeval(num, TRUE);
2850}
2851
2852struct timeval
2854{
2855 struct time_object *tobj;
2856 struct timeval t;
2857 struct timespec ts;
2858
2859 if (IsTimeval(time)) {
2860 GetTimeval(time, tobj);
2861 ts = timew2timespec(tobj->timew);
2862 t.tv_sec = (TYPEOF_TIMEVAL_TV_SEC)ts.tv_sec;
2863 t.tv_usec = (TYPEOF_TIMEVAL_TV_USEC)(ts.tv_nsec / 1000);
2864 return t;
2865 }
2866 return time_timeval(time, FALSE);
2867}
2868
2869struct timespec
2871{
2872 struct time_object *tobj;
2873 struct timespec t;
2874
2875 if (IsTimeval(time)) {
2876 GetTimeval(time, tobj);
2877 t = timew2timespec(tobj->timew);
2878 return t;
2879 }
2880 return time_timespec(time, FALSE);
2881}
2882
2883struct timespec
2885{
2886 return time_timespec(num, TRUE);
2887}
2888
2889static int
2890get_scale(VALUE unit)
2891{
2892 if (unit == ID2SYM(id_nanosecond) || unit == ID2SYM(id_nsec)) {
2893 return 1000000000;
2894 }
2895 else if (unit == ID2SYM(id_microsecond) || unit == ID2SYM(id_usec)) {
2896 return 1000000;
2897 }
2898 else if (unit == ID2SYM(id_millisecond)) {
2899 return 1000;
2900 }
2901 else {
2902 rb_raise(rb_eArgError, "unexpected unit: %"PRIsVALUE, unit);
2903 }
2904}
2905
2906static VALUE
2907time_s_at(rb_execution_context_t *ec, VALUE klass, VALUE time, VALUE subsec, VALUE unit, VALUE zone)
2908{
2909 VALUE t;
2910 wideval_t timew;
2911
2912 if (subsec) {
2913 int scale = get_scale(unit);
2914 time = num_exact(time);
2915 t = num_exact(subsec);
2916 timew = wadd(rb_time_magnify(v2w(time)), wmulquoll(v2w(t), TIME_SCALE, scale));
2917 t = time_new_timew(klass, timew);
2918 }
2919 else if (IsTimeval(time)) {
2920 struct time_object *tobj, *tobj2;
2921 GetTimeval(time, tobj);
2922 t = time_new_timew(klass, tobj->timew);
2923 GetTimeval(t, tobj2);
2924 TZMODE_COPY(tobj2, tobj);
2925 }
2926 else {
2927 timew = rb_time_magnify(v2w(num_exact(time)));
2928 t = time_new_timew(klass, timew);
2929 }
2930 if (!NIL_P(zone)) {
2931 time_zonelocal(t, zone);
2932 }
2933
2934 return t;
2935}
2936
2937static VALUE
2938time_s_at1(rb_execution_context_t *ec, VALUE klass, VALUE time)
2939{
2940 return time_s_at(ec, klass, time, Qfalse, ID2SYM(id_microsecond), Qnil);
2941}
2942
2943static const char months[][4] = {
2944 "jan", "feb", "mar", "apr", "may", "jun",
2945 "jul", "aug", "sep", "oct", "nov", "dec",
2946};
2947
2948static int
2949obj2int(VALUE obj)
2950{
2951 if (RB_TYPE_P(obj, T_STRING)) {
2952 obj = rb_str_to_inum(obj, 10, TRUE);
2953 }
2954
2955 return NUM2INT(obj);
2956}
2957
2958/* bits should be 0 <= x <= 31 */
2959static uint32_t
2960obj2ubits(VALUE obj, unsigned int bits)
2961{
2962 const unsigned int usable_mask = (1U << bits) - 1;
2963 unsigned int rv = (unsigned int)obj2int(obj);
2964
2965 if ((rv & usable_mask) != rv)
2966 rb_raise(rb_eArgError, "argument out of range");
2967 return (uint32_t)rv;
2968}
2969
2970static VALUE
2971obj2vint(VALUE obj)
2972{
2973 if (RB_TYPE_P(obj, T_STRING)) {
2974 obj = rb_str_to_inum(obj, 10, TRUE);
2975 }
2976 else {
2977 obj = rb_to_int(obj);
2978 }
2979
2980 return obj;
2981}
2982
2983static uint32_t
2984obj2subsecx(VALUE obj, VALUE *subsecx)
2985{
2986 VALUE subsec;
2987
2988 if (RB_TYPE_P(obj, T_STRING)) {
2989 obj = rb_str_to_inum(obj, 10, TRUE);
2990 *subsecx = INT2FIX(0);
2991 }
2992 else {
2993 divmodv(num_exact(obj), INT2FIX(1), &obj, &subsec);
2994 *subsecx = w2v(rb_time_magnify(v2w(subsec)));
2995 }
2996 return obj2ubits(obj, 6); /* vtm->sec */
2997}
2998
2999static VALUE
3000usec2subsecx(VALUE obj)
3001{
3002 if (RB_TYPE_P(obj, T_STRING)) {
3003 obj = rb_str_to_inum(obj, 10, TRUE);
3004 }
3005
3006 return mulquov(num_exact(obj), INT2FIX(TIME_SCALE), INT2FIX(1000000));
3007}
3008
3009static uint32_t
3010month_arg(VALUE arg)
3011{
3012 int i, mon;
3013
3014 if (FIXNUM_P(arg)) {
3015 return obj2ubits(arg, 4);
3016 }
3017
3018 mon = 0;
3019 VALUE s = rb_check_string_type(arg);
3020 if (!NIL_P(s) && RSTRING_LEN(s) > 0) {
3021 arg = s;
3022 for (i=0; i<12; i++) {
3023 if (RSTRING_LEN(s) == 3 &&
3024 STRNCASECMP(months[i], RSTRING_PTR(s), 3) == 0) {
3025 mon = i+1;
3026 break;
3027 }
3028 }
3029 }
3030 if (mon == 0) {
3031 mon = obj2ubits(arg, 4);
3032 }
3033 return mon;
3034}
3035
3036static VALUE
3037validate_utc_offset(VALUE utc_offset)
3038{
3039 if (le(utc_offset, INT2FIX(-86400)) || ge(utc_offset, INT2FIX(86400)))
3040 rb_raise(rb_eArgError, "utc_offset out of range");
3041 return utc_offset;
3042}
3043
3044static VALUE
3045validate_zone_name(VALUE zone_name)
3046{
3047 StringValueCStr(zone_name);
3048 return zone_name;
3049}
3050
3051static void
3052validate_vtm(struct vtm *vtm)
3053{
3054#define validate_vtm_range(mem, b, e) \
3055 ((vtm->mem < b || vtm->mem > e) ? \
3056 rb_raise(rb_eArgError, #mem" out of range") : (void)0)
3057 validate_vtm_range(mon, 1, 12);
3058 validate_vtm_range(mday, 1, 31);
3059 validate_vtm_range(hour, 0, 24);
3060 validate_vtm_range(min, 0, (vtm->hour == 24 ? 0 : 59));
3061 validate_vtm_range(sec, 0, (vtm->hour == 24 ? 0 : 60));
3062 if (lt(vtm->subsecx, INT2FIX(0)) || ge(vtm->subsecx, INT2FIX(TIME_SCALE)))
3063 rb_raise(rb_eArgError, "subsecx out of range");
3064 if (!NIL_P(vtm->utc_offset)) validate_utc_offset(vtm->utc_offset);
3065#undef validate_vtm_range
3066}
3067
3068static void
3069time_arg(int argc, const VALUE *argv, struct vtm *vtm)
3070{
3071 VALUE v[8];
3072 VALUE subsecx = INT2FIX(0);
3073
3074 vtm->year = INT2FIX(0);
3075 vtm->mon = 0;
3076 vtm->mday = 0;
3077 vtm->hour = 0;
3078 vtm->min = 0;
3079 vtm->sec = 0;
3080 vtm->subsecx = INT2FIX(0);
3081 vtm->utc_offset = Qnil;
3082 vtm->wday = 0;
3083 vtm->yday = 0;
3084 vtm->isdst = 0;
3085 vtm->zone = str_empty;
3086
3087 if (argc == 10) {
3088 v[0] = argv[5];
3089 v[1] = argv[4];
3090 v[2] = argv[3];
3091 v[3] = argv[2];
3092 v[4] = argv[1];
3093 v[5] = argv[0];
3094 v[6] = Qnil;
3095 vtm->isdst = RTEST(argv[8]) ? 1 : 0;
3096 }
3097 else {
3098 rb_scan_args(argc, argv, "17", &v[0],&v[1],&v[2],&v[3],&v[4],&v[5],&v[6],&v[7]);
3099 /* v[6] may be usec or zone (parsedate) */
3100 /* v[7] is wday (parsedate; ignored) */
3101 vtm->wday = VTM_WDAY_INITVAL;
3102 vtm->isdst = VTM_ISDST_INITVAL;
3103 }
3104
3105 vtm->year = obj2vint(v[0]);
3106
3107 if (NIL_P(v[1])) {
3108 vtm->mon = 1;
3109 }
3110 else {
3111 vtm->mon = month_arg(v[1]);
3112 }
3113
3114 if (NIL_P(v[2])) {
3115 vtm->mday = 1;
3116 }
3117 else {
3118 vtm->mday = obj2ubits(v[2], 5);
3119 }
3120
3121 /* normalize month-mday */
3122 switch (vtm->mon) {
3123 case 2:
3124 {
3125 /* this drops higher bits but it's not a problem to calc leap year */
3126 unsigned int mday2 = leap_year_v_p(vtm->year) ? 29 : 28;
3127 if (vtm->mday > mday2) {
3128 vtm->mday -= mday2;
3129 vtm->mon++;
3130 }
3131 }
3132 break;
3133 case 4:
3134 case 6:
3135 case 9:
3136 case 11:
3137 if (vtm->mday == 31) {
3138 vtm->mon++;
3139 vtm->mday = 1;
3140 }
3141 break;
3142 }
3143
3144 vtm->hour = NIL_P(v[3])?0:obj2ubits(v[3], 5);
3145
3146 vtm->min = NIL_P(v[4])?0:obj2ubits(v[4], 6);
3147
3148 if (!NIL_P(v[6]) && argc == 7) {
3149 vtm->sec = NIL_P(v[5])?0:obj2ubits(v[5],6);
3150 subsecx = usec2subsecx(v[6]);
3151 }
3152 else {
3153 /* when argc == 8, v[6] is timezone, but ignored */
3154 if (NIL_P(v[5])) {
3155 vtm->sec = 0;
3156 }
3157 else {
3158 vtm->sec = obj2subsecx(v[5], &subsecx);
3159 }
3160 }
3161 vtm->subsecx = subsecx;
3162
3163 validate_vtm(vtm);
3164 RB_GC_GUARD(subsecx);
3165}
3166
3167static int
3168leap_year_p(long y)
3169{
3170 /* TODO:
3171 * ensure about negative years in proleptic Gregorian calendar.
3172 */
3173 unsigned long uy = (unsigned long)(LIKELY(y >= 0) ? y : -y);
3174
3175 if (LIKELY(uy % 4 != 0)) return 0;
3176
3177 unsigned long century = uy / 100;
3178 if (LIKELY(uy != century * 100)) return 1;
3179 return century % 4 == 0;
3180}
3181
3182static time_t
3183timegm_noleapsecond(struct tm *tm)
3184{
3185 long tm_year = tm->tm_year;
3186 int tm_yday = calc_tm_yday(tm->tm_year, tm->tm_mon, tm->tm_mday);
3187
3188 /*
3189 * `Seconds Since the Epoch' in SUSv3:
3190 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
3191 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
3192 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
3193 */
3194 return tm->tm_sec + tm->tm_min*60 + tm->tm_hour*3600 +
3195 (time_t)(tm_yday +
3196 (tm_year-70)*365 +
3197 DIV(tm_year-69,4) -
3198 DIV(tm_year-1,100) +
3199 DIV(tm_year+299,400))*86400;
3200}
3201
3202#if 0
3203#define DEBUG_FIND_TIME_NUMGUESS
3204#define DEBUG_GUESSRANGE
3205#endif
3206
3207static const bool debug_guessrange =
3208#ifdef DEBUG_GUESSRANGE
3209 true;
3210#else
3211 false;
3212#endif
3213
3214#define DEBUG_REPORT_GUESSRANGE \
3215 (debug_guessrange ? debug_report_guessrange(guess_lo, guess_hi) : (void)0)
3216
3217static inline void
3218debug_report_guessrange(time_t guess_lo, time_t guess_hi)
3219{
3220 time_t guess_diff = guess_hi - guess_lo;
3221 fprintf(stderr, "find time guess range: %"PRI_TIMET_PREFIX"d - "
3222 "%"PRI_TIMET_PREFIX"d : %"PRI_TIMET_PREFIX"u\n",
3223 guess_lo, guess_hi, guess_diff);
3224}
3225
3226static const bool debug_find_time_numguess =
3227#ifdef DEBUG_FIND_TIME_NUMGUESS
3228 true;
3229#else
3230 false;
3231#endif
3232
3233#define DEBUG_FIND_TIME_NUMGUESS_INC \
3234 (void)(debug_find_time_numguess && find_time_numguess++),
3235static unsigned long long find_time_numguess;
3236
3237static VALUE
3238find_time_numguess_getter(ID name, VALUE *data)
3239{
3240 unsigned long long *numguess = (void *)data;
3241 return ULL2NUM(*numguess);
3242}
3243
3244static const char *
3245find_time_t(struct tm *tptr, int utc_p, time_t *tp)
3246{
3247 time_t guess, guess0, guess_lo, guess_hi;
3248 struct tm *tm, tm0, tm_lo, tm_hi;
3249 int d;
3250 int find_dst;
3251 struct tm result;
3252 int status;
3253 int tptr_tm_yday;
3254
3255#define GUESS(p) (DEBUG_FIND_TIME_NUMGUESS_INC (utc_p ? gmtime_with_leapsecond((p), &result) : LOCALTIME((p), result)))
3256
3257 guess_lo = TIMET_MIN;
3258 guess_hi = TIMET_MAX;
3259
3260 find_dst = 0 < tptr->tm_isdst;
3261
3262 /* /etc/localtime might be changed. reload it. */
3263 update_tz();
3264
3265 tm0 = *tptr;
3266 if (tm0.tm_mon < 0) {
3267 tm0.tm_mon = 0;
3268 tm0.tm_mday = 1;
3269 tm0.tm_hour = 0;
3270 tm0.tm_min = 0;
3271 tm0.tm_sec = 0;
3272 }
3273 else if (11 < tm0.tm_mon) {
3274 tm0.tm_mon = 11;
3275 tm0.tm_mday = 31;
3276 tm0.tm_hour = 23;
3277 tm0.tm_min = 59;
3278 tm0.tm_sec = 60;
3279 }
3280 else if (tm0.tm_mday < 1) {
3281 tm0.tm_mday = 1;
3282 tm0.tm_hour = 0;
3283 tm0.tm_min = 0;
3284 tm0.tm_sec = 0;
3285 }
3286 else if ((d = days_in_month_in(1900 + tm0.tm_year)[tm0.tm_mon]) < tm0.tm_mday) {
3287 tm0.tm_mday = d;
3288 tm0.tm_hour = 23;
3289 tm0.tm_min = 59;
3290 tm0.tm_sec = 60;
3291 }
3292 else if (tm0.tm_hour < 0) {
3293 tm0.tm_hour = 0;
3294 tm0.tm_min = 0;
3295 tm0.tm_sec = 0;
3296 }
3297 else if (23 < tm0.tm_hour) {
3298 tm0.tm_hour = 23;
3299 tm0.tm_min = 59;
3300 tm0.tm_sec = 60;
3301 }
3302 else if (tm0.tm_min < 0) {
3303 tm0.tm_min = 0;
3304 tm0.tm_sec = 0;
3305 }
3306 else if (59 < tm0.tm_min) {
3307 tm0.tm_min = 59;
3308 tm0.tm_sec = 60;
3309 }
3310 else if (tm0.tm_sec < 0) {
3311 tm0.tm_sec = 0;
3312 }
3313 else if (60 < tm0.tm_sec) {
3314 tm0.tm_sec = 60;
3315 }
3316
3317 DEBUG_REPORT_GUESSRANGE;
3318 guess0 = guess = timegm_noleapsecond(&tm0);
3319 tm = GUESS(&guess);
3320 if (tm) {
3321 d = tmcmp(tptr, tm);
3322 if (d == 0) { goto found; }
3323 if (d < 0) {
3324 guess_hi = guess;
3325 guess -= 24 * 60 * 60;
3326 }
3327 else {
3328 guess_lo = guess;
3329 guess += 24 * 60 * 60;
3330 }
3331 DEBUG_REPORT_GUESSRANGE;
3332 if (guess_lo < guess && guess < guess_hi && (tm = GUESS(&guess)) != NULL) {
3333 d = tmcmp(tptr, tm);
3334 if (d == 0) { goto found; }
3335 if (d < 0)
3336 guess_hi = guess;
3337 else
3338 guess_lo = guess;
3339 DEBUG_REPORT_GUESSRANGE;
3340 }
3341 }
3342
3343 tm = GUESS(&guess_lo);
3344 if (!tm) goto error;
3345 d = tmcmp(tptr, tm);
3346 if (d < 0) goto out_of_range;
3347 if (d == 0) { guess = guess_lo; goto found; }
3348 tm_lo = *tm;
3349
3350 tm = GUESS(&guess_hi);
3351 if (!tm) goto error;
3352 d = tmcmp(tptr, tm);
3353 if (d > 0) goto out_of_range;
3354 if (d == 0) { guess = guess_hi; goto found; }
3355 tm_hi = *tm;
3356
3357 DEBUG_REPORT_GUESSRANGE;
3358
3359 status = 1;
3360
3361 while (guess_lo + 1 < guess_hi) {
3362 binsearch:
3363 if (status == 0) {
3364 guess = guess_lo / 2 + guess_hi / 2;
3365 if (guess <= guess_lo)
3366 guess = guess_lo + 1;
3367 else if (guess >= guess_hi)
3368 guess = guess_hi - 1;
3369 status = 1;
3370 }
3371 else {
3372 if (status == 1) {
3373 time_t guess0_hi = timegm_noleapsecond(&tm_hi);
3374 guess = guess_hi - (guess0_hi - guess0);
3375 if (guess == guess_hi) /* hh:mm:60 tends to cause this condition. */
3376 guess--;
3377 status = 2;
3378 }
3379 else if (status == 2) {
3380 time_t guess0_lo = timegm_noleapsecond(&tm_lo);
3381 guess = guess_lo + (guess0 - guess0_lo);
3382 if (guess == guess_lo)
3383 guess++;
3384 status = 0;
3385 }
3386 if (guess <= guess_lo || guess_hi <= guess) {
3387 /* Previous guess is invalid. try binary search. */
3388 if (debug_guessrange) {
3389 if (guess <= guess_lo) {
3390 fprintf(stderr, "too small guess: %"PRI_TIMET_PREFIX"d"\
3391 " <= %"PRI_TIMET_PREFIX"d\n", guess, guess_lo);
3392 }
3393 if (guess_hi <= guess) {
3394 fprintf(stderr, "too big guess: %"PRI_TIMET_PREFIX"d"\
3395 " <= %"PRI_TIMET_PREFIX"d\n", guess_hi, guess);
3396 }
3397 }
3398 status = 0;
3399 goto binsearch;
3400 }
3401 }
3402
3403 tm = GUESS(&guess);
3404 if (!tm) goto error;
3405
3406 d = tmcmp(tptr, tm);
3407
3408 if (d < 0) {
3409 guess_hi = guess;
3410 tm_hi = *tm;
3411 DEBUG_REPORT_GUESSRANGE;
3412 }
3413 else if (d > 0) {
3414 guess_lo = guess;
3415 tm_lo = *tm;
3416 DEBUG_REPORT_GUESSRANGE;
3417 }
3418 else {
3419 goto found;
3420 }
3421 }
3422
3423 /* Given argument has no corresponding time_t. Let's extrapolate. */
3424 /*
3425 * `Seconds Since the Epoch' in SUSv3:
3426 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
3427 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
3428 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
3429 */
3430
3431 tptr_tm_yday = calc_tm_yday(tptr->tm_year, tptr->tm_mon, tptr->tm_mday);
3432
3433 *tp = guess_lo +
3434 ((tptr->tm_year - tm_lo.tm_year) * 365 +
3435 DIV((tptr->tm_year-69), 4) -
3436 DIV((tptr->tm_year-1), 100) +
3437 DIV((tptr->tm_year+299), 400) -
3438 DIV((tm_lo.tm_year-69), 4) +
3439 DIV((tm_lo.tm_year-1), 100) -
3440 DIV((tm_lo.tm_year+299), 400) +
3441 tptr_tm_yday -
3442 tm_lo.tm_yday) * 86400 +
3443 (tptr->tm_hour - tm_lo.tm_hour) * 3600 +
3444 (tptr->tm_min - tm_lo.tm_min) * 60 +
3445 (tptr->tm_sec - (tm_lo.tm_sec == 60 ? 59 : tm_lo.tm_sec));
3446
3447 return NULL;
3448
3449 found:
3450 if (!utc_p) {
3451 /* If localtime is nonmonotonic, another result may exist. */
3452 time_t guess2;
3453 if (find_dst) {
3454 guess2 = guess - 2 * 60 * 60;
3455 tm = LOCALTIME(&guess2, result);
3456 if (tm) {
3457 if (tptr->tm_hour != (tm->tm_hour + 2) % 24 ||
3458 tptr->tm_min != tm->tm_min ||
3459 tptr->tm_sec != tm->tm_sec) {
3460 guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
3461 (tm->tm_min - tptr->tm_min) * 60 +
3462 (tm->tm_sec - tptr->tm_sec);
3463 if (tptr->tm_mday != tm->tm_mday)
3464 guess2 += 24 * 60 * 60;
3465 if (guess != guess2) {
3466 tm = LOCALTIME(&guess2, result);
3467 if (tm && tmcmp(tptr, tm) == 0) {
3468 if (guess < guess2)
3469 *tp = guess;
3470 else
3471 *tp = guess2;
3472 return NULL;
3473 }
3474 }
3475 }
3476 }
3477 }
3478 else {
3479 guess2 = guess + 2 * 60 * 60;
3480 tm = LOCALTIME(&guess2, result);
3481 if (tm) {
3482 if ((tptr->tm_hour + 2) % 24 != tm->tm_hour ||
3483 tptr->tm_min != tm->tm_min ||
3484 tptr->tm_sec != tm->tm_sec) {
3485 guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
3486 (tm->tm_min - tptr->tm_min) * 60 +
3487 (tm->tm_sec - tptr->tm_sec);
3488 if (tptr->tm_mday != tm->tm_mday)
3489 guess2 -= 24 * 60 * 60;
3490 if (guess != guess2) {
3491 tm = LOCALTIME(&guess2, result);
3492 if (tm && tmcmp(tptr, tm) == 0) {
3493 if (guess < guess2)
3494 *tp = guess2;
3495 else
3496 *tp = guess;
3497 return NULL;
3498 }
3499 }
3500 }
3501 }
3502 }
3503 }
3504 *tp = guess;
3505 return NULL;
3506
3507 out_of_range:
3508 return "time out of range";
3509
3510 error:
3511 return "gmtime/localtime error";
3512}
3513
3514static int
3515vtmcmp(struct vtm *a, struct vtm *b)
3516{
3517 if (ne(a->year, b->year))
3518 return lt(a->year, b->year) ? -1 : 1;
3519 else if (a->mon != b->mon)
3520 return a->mon < b->mon ? -1 : 1;
3521 else if (a->mday != b->mday)
3522 return a->mday < b->mday ? -1 : 1;
3523 else if (a->hour != b->hour)
3524 return a->hour < b->hour ? -1 : 1;
3525 else if (a->min != b->min)
3526 return a->min < b->min ? -1 : 1;
3527 else if (a->sec != b->sec)
3528 return a->sec < b->sec ? -1 : 1;
3529 else if (ne(a->subsecx, b->subsecx))
3530 return lt(a->subsecx, b->subsecx) ? -1 : 1;
3531 else
3532 return 0;
3533}
3534
3535static int
3536tmcmp(struct tm *a, struct tm *b)
3537{
3538 if (a->tm_year != b->tm_year)
3539 return a->tm_year < b->tm_year ? -1 : 1;
3540 else if (a->tm_mon != b->tm_mon)
3541 return a->tm_mon < b->tm_mon ? -1 : 1;
3542 else if (a->tm_mday != b->tm_mday)
3543 return a->tm_mday < b->tm_mday ? -1 : 1;
3544 else if (a->tm_hour != b->tm_hour)
3545 return a->tm_hour < b->tm_hour ? -1 : 1;
3546 else if (a->tm_min != b->tm_min)
3547 return a->tm_min < b->tm_min ? -1 : 1;
3548 else if (a->tm_sec != b->tm_sec)
3549 return a->tm_sec < b->tm_sec ? -1 : 1;
3550 else
3551 return 0;
3552}
3553
3554/*
3555 * call-seq:
3556 * Time.utc(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0) -> new_time
3557 * Time.utc(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy) -> new_time
3558 *
3559 * Returns a new \Time object based the on given arguments,
3560 * in the UTC timezone.
3561 *
3562 * With one to seven arguments given,
3563 * the arguments are interpreted as in the first calling sequence above:
3564 *
3565 * Time.utc(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0)
3566 *
3567 * Examples:
3568 *
3569 * Time.utc(2000) # => 2000-01-01 00:00:00 UTC
3570 * Time.utc(-2000) # => -2000-01-01 00:00:00 UTC
3571 *
3572 * There are no minimum and maximum values for the required argument +year+.
3573 *
3574 * For the optional arguments:
3575 *
3576 * - +month+: Month in range (1..12), or case-insensitive
3577 * 3-letter month name:
3578 *
3579 * Time.utc(2000, 1) # => 2000-01-01 00:00:00 UTC
3580 * Time.utc(2000, 12) # => 2000-12-01 00:00:00 UTC
3581 * Time.utc(2000, 'jan') # => 2000-01-01 00:00:00 UTC
3582 * Time.utc(2000, 'JAN') # => 2000-01-01 00:00:00 UTC
3583 *
3584 * - +mday+: Month day in range(1..31):
3585 *
3586 * Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC
3587 * Time.utc(2000, 1, 31) # => 2000-01-31 00:00:00 UTC
3588 *
3589 * - +hour+: Hour in range (0..23), or 24 if +min+, +sec+, and +usec+
3590 * are zero:
3591 *
3592 * Time.utc(2000, 1, 1, 0) # => 2000-01-01 00:00:00 UTC
3593 * Time.utc(2000, 1, 1, 23) # => 2000-01-01 23:00:00 UTC
3594 * Time.utc(2000, 1, 1, 24) # => 2000-01-02 00:00:00 UTC
3595 *
3596 * - +min+: Minute in range (0..59):
3597 *
3598 * Time.utc(2000, 1, 1, 0, 0) # => 2000-01-01 00:00:00 UTC
3599 * Time.utc(2000, 1, 1, 0, 59) # => 2000-01-01 00:59:00 UTC
3600 *
3601 * - +sec+: Second in range (0..59), or 60 if +usec+ is zero:
3602 *
3603 * Time.utc(2000, 1, 1, 0, 0, 0) # => 2000-01-01 00:00:00 UTC
3604 * Time.utc(2000, 1, 1, 0, 0, 59) # => 2000-01-01 00:00:59 UTC
3605 * Time.utc(2000, 1, 1, 0, 0, 60) # => 2000-01-01 00:01:00 UTC
3606 *
3607 * - +usec+: Microsecond in range (0..999999):
3608 *
3609 * Time.utc(2000, 1, 1, 0, 0, 0, 0) # => 2000-01-01 00:00:00 UTC
3610 * Time.utc(2000, 1, 1, 0, 0, 0, 999999) # => 2000-01-01 00:00:00.999999 UTC
3611 *
3612 * The values may be:
3613 *
3614 * - Integers, as above.
3615 * - Numerics convertible to integers:
3616 *
3617 * Time.utc(Float(0.0), Rational(1, 1), 1.0, 0.0, 0.0, 0.0, 0.0)
3618 * # => 0000-01-01 00:00:00 UTC
3619 *
3620 * - \String integers:
3621 *
3622 * a = %w[0 1 1 0 0 0 0 0]
3623 * # => ["0", "1", "1", "0", "0", "0", "0", "0"]
3624 * Time.utc(*a) # => 0000-01-01 00:00:00 UTC
3625 *
3626 * When exactly ten arguments are given,
3627 * the arguments are interpreted as in the second calling sequence above:
3628 *
3629 * Time.utc(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy)
3630 *
3631 * where the +dummy+ arguments are ignored:
3632 *
3633 * a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3634 * # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3635 * Time.utc(*a) # => 0005-04-03 02:01:00 UTC
3636 *
3637 * This form is useful for creating a \Time object from a 10-element
3638 * array returned by Time.to_a:
3639 *
3640 * t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006
3641 * a = t.to_a # => [5, 4, 3, 2, 1, 2000, 0, 2, false, nil]
3642 * Time.utc(*a) # => 2000-01-02 03:04:05 UTC
3643 *
3644 * The two forms have their first six arguments in common,
3645 * though in different orders;
3646 * the ranges of these common arguments are the same for both forms; see above.
3647 *
3648 * Raises an exception if the number of arguments is eight, nine,
3649 * or greater than ten.
3650 *
3651 * Time.gm is an alias for Time.utc.
3652 *
3653 * Related: Time.local.
3654 *
3655 */
3656static VALUE
3657time_s_mkutc(int argc, VALUE *argv, VALUE klass)
3658{
3659 struct vtm vtm;
3660
3661 time_arg(argc, argv, &vtm);
3662 return time_gmtime(time_new_timew(klass, timegmw(&vtm)));
3663}
3664
3665/*
3666 * call-seq:
3667 * Time.local(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0) -> new_time
3668 * Time.local(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy) -> new_time
3669 *
3670 * Like Time.utc, except that the returned \Time object
3671 * has the local timezone, not the UTC timezone:
3672 *
3673 * # With seven arguments.
3674 * Time.local(0, 1, 2, 3, 4, 5, 6)
3675 * # => 0000-01-02 03:04:05.000006 -0600
3676 * # With exactly ten arguments.
3677 * Time.local(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
3678 * # => 0005-04-03 02:01:00 -0600
3679 *
3680 */
3681
3682static VALUE
3683time_s_mktime(int argc, VALUE *argv, VALUE klass)
3684{
3685 struct vtm vtm;
3686
3687 time_arg(argc, argv, &vtm);
3688 return time_localtime(time_new_timew(klass, timelocalw(&vtm)));
3689}
3690
3691/*
3692 * call-seq:
3693 * to_i -> integer
3694 *
3695 * Returns the value of +self+ as integer
3696 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3697 * subseconds are truncated (not rounded):
3698 *
3699 * Time.utc(1970, 1, 1, 0, 0, 0).to_i # => 0
3700 * Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_i # => 0
3701 * Time.utc(1950, 1, 1, 0, 0, 0).to_i # => -631152000
3702 * Time.utc(1990, 1, 1, 0, 0, 0).to_i # => 631152000
3703 *
3704 * Time#tv_sec is an alias for Time#to_i.
3705 *
3706 * Related: Time#to_f Time#to_r.
3707 */
3708
3709static VALUE
3710time_to_i(VALUE time)
3711{
3712 struct time_object *tobj;
3713
3714 GetTimeval(time, tobj);
3715 return w2v(wdiv(tobj->timew, WINT2FIXWV(TIME_SCALE)));
3716}
3717
3718/*
3719 * call-seq:
3720 * to_f -> float
3721 *
3722 * Returns the value of +self+ as a Float number
3723 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3724 * subseconds are included.
3725 *
3726 * The stored value of +self+ is a
3727 * {Rational}[rdoc-ref:Rational@#method-i-to_f],
3728 * which means that the returned value may be approximate:
3729 *
3730 * Time.utc(1970, 1, 1, 0, 0, 0).to_f # => 0.0
3731 * Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_f # => 0.999999
3732 * Time.utc(1950, 1, 1, 0, 0, 0).to_f # => -631152000.0
3733 * Time.utc(1990, 1, 1, 0, 0, 0).to_f # => 631152000.0
3734 *
3735 * Related: Time#to_i, Time#to_r.
3736 */
3737
3738static VALUE
3739time_to_f(VALUE time)
3740{
3741 struct time_object *tobj;
3742
3743 GetTimeval(time, tobj);
3744 return rb_Float(rb_time_unmagnify_to_float(tobj->timew));
3745}
3746
3747/*
3748 * call-seq:
3749 * to_r -> rational
3750 *
3751 * Returns the value of +self+ as a Rational exact number of
3752 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3753 *
3754 * Time.now.to_r # => (16571402750320203/10000000)
3755 *
3756 * Related: Time#to_f, Time#to_i.
3757 */
3758
3759static VALUE
3760time_to_r(VALUE time)
3761{
3762 struct time_object *tobj;
3763 VALUE v;
3764
3765 GetTimeval(time, tobj);
3766 v = rb_time_unmagnify_to_rational(tobj->timew);
3767 if (!RB_TYPE_P(v, T_RATIONAL)) {
3768 v = rb_Rational1(v);
3769 }
3770 return v;
3771}
3772
3773/*
3774 * call-seq:
3775 * usec -> integer
3776 *
3777 * Returns the number of microseconds in the subseconds part of +self+
3778 * in the range (0..999_999);
3779 * lower-order digits are truncated, not rounded:
3780 *
3781 * t = Time.now # => 2022-07-11 14:59:47.5484697 -0500
3782 * t.usec # => 548469
3783 *
3784 * Related: Time#subsec (returns exact subseconds).
3785 *
3786 * Time#tv_usec is an alias for Time#usec.
3787 */
3788
3789static VALUE
3790time_usec(VALUE time)
3791{
3792 struct time_object *tobj;
3793 wideval_t w, q, r;
3794
3795 GetTimeval(time, tobj);
3796
3797 w = wmod(tobj->timew, WINT2WV(TIME_SCALE));
3798 wmuldivmod(w, WINT2FIXWV(1000000), WINT2FIXWV(TIME_SCALE), &q, &r);
3799 return rb_to_int(w2v(q));
3800}
3801
3802/*
3803 * call-seq:
3804 * nsec -> integer
3805 *
3806 * Returns the number of nanoseconds in the subseconds part of +self+
3807 * in the range (0..999_999_999);
3808 * lower-order digits are truncated, not rounded:
3809 *
3810 * t = Time.now # => 2022-07-11 15:04:53.3219637 -0500
3811 * t.nsec # => 321963700
3812 *
3813 * Related: Time#subsec (returns exact subseconds).
3814 *
3815 * Time#tv_nsec is an alias for Time#usec.
3816 */
3817
3818static VALUE
3819time_nsec(VALUE time)
3820{
3821 struct time_object *tobj;
3822
3823 GetTimeval(time, tobj);
3824 return rb_to_int(w2v(wmulquoll(wmod(tobj->timew, WINT2WV(TIME_SCALE)), 1000000000, TIME_SCALE)));
3825}
3826
3827/*
3828 * call-seq:
3829 * subsec -> numeric
3830 *
3831 * Returns the exact subseconds for +self+ as a Numeric
3832 * (Integer or Rational):
3833 *
3834 * t = Time.now # => 2022-07-11 15:11:36.8490302 -0500
3835 * t.subsec # => (4245151/5000000)
3836 *
3837 * If the subseconds is zero, returns integer zero:
3838 *
3839 * t = Time.new(2000, 1, 1, 2, 3, 4) # => 2000-01-01 02:03:04 -0600
3840 * t.subsec # => 0
3841 *
3842 */
3843
3844static VALUE
3845time_subsec(VALUE time)
3846{
3847 struct time_object *tobj;
3848
3849 GetTimeval(time, tobj);
3850 return quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE));
3851}
3852
3853/*
3854 * call-seq:
3855 * self <=> other_time -> -1, 0, +1, or nil
3856 *
3857 * Compares +self+ with +other_time+; returns:
3858 *
3859 * - +-1+, if +self+ is less than +other_time+.
3860 * - +0+, if +self+ is equal to +other_time+.
3861 * - +1+, if +self+ is greater then +other_time+.
3862 * - +nil+, if +self+ and +other_time+ are incomparable.
3863 *
3864 * Examples:
3865 *
3866 * t = Time.now # => 2007-11-19 08:12:12 -0600
3867 * t2 = t + 2592000 # => 2007-12-19 08:12:12 -0600
3868 * t <=> t2 # => -1
3869 * t2 <=> t # => 1
3870 *
3871 * t = Time.now # => 2007-11-19 08:13:38 -0600
3872 * t2 = t + 0.1 # => 2007-11-19 08:13:38 -0600
3873 * t.nsec # => 98222999
3874 * t2.nsec # => 198222999
3875 * t <=> t2 # => -1
3876 * t2 <=> t # => 1
3877 * t <=> t # => 0
3878 *
3879 */
3880
3881static VALUE
3882time_cmp(VALUE time1, VALUE time2)
3883{
3884 struct time_object *tobj1, *tobj2;
3885 int n;
3886
3887 GetTimeval(time1, tobj1);
3888 if (IsTimeval(time2)) {
3889 GetTimeval(time2, tobj2);
3890 n = wcmp(tobj1->timew, tobj2->timew);
3891 }
3892 else {
3893 return rb_invcmp(time1, time2);
3894 }
3895 if (n == 0) return INT2FIX(0);
3896 if (n > 0) return INT2FIX(1);
3897 return INT2FIX(-1);
3898}
3899
3900/*
3901 * call-seq:
3902 * eql?(other_time)
3903 *
3904 * Returns +true+ if +self+ and +other_time+ are
3905 * both \Time objects with the exact same time value.
3906 */
3907
3908static VALUE
3909time_eql(VALUE time1, VALUE time2)
3910{
3911 struct time_object *tobj1, *tobj2;
3912
3913 GetTimeval(time1, tobj1);
3914 if (IsTimeval(time2)) {
3915 GetTimeval(time2, tobj2);
3916 return rb_equal(w2v(tobj1->timew), w2v(tobj2->timew));
3917 }
3918 return Qfalse;
3919}
3920
3921/*
3922 * call-seq:
3923 * utc? -> true or false
3924 *
3925 * Returns +true+ if +self+ represents a time in UTC (GMT):
3926 *
3927 * now = Time.now
3928 * # => 2022-08-18 10:24:13.5398485 -0500
3929 * now.utc? # => false
3930 * utc = Time.utc(2000, 1, 1, 20, 15, 1)
3931 * # => 2000-01-01 20:15:01 UTC
3932 * utc.utc? # => true
3933 *
3934 * Time#gmt? is an alias for Time#utc?.
3935 *
3936 * Related: Time.utc.
3937 */
3938
3939static VALUE
3940time_utc_p(VALUE time)
3941{
3942 struct time_object *tobj;
3943
3944 GetTimeval(time, tobj);
3945 return RBOOL(TZMODE_UTC_P(tobj));
3946}
3947
3948/*
3949 * call-seq:
3950 * hash -> integer
3951 *
3952 * Returns the integer hash code for +self+.
3953 *
3954 * Related: Object#hash.
3955 */
3956
3957static VALUE
3958time_hash(VALUE time)
3959{
3960 struct time_object *tobj;
3961
3962 GetTimeval(time, tobj);
3963 return rb_hash(w2v(tobj->timew));
3964}
3965
3966/* :nodoc: */
3967static VALUE
3968time_init_copy(VALUE copy, VALUE time)
3969{
3970 struct time_object *tobj, *tcopy;
3971
3972 if (!OBJ_INIT_COPY(copy, time)) return copy;
3973 GetTimeval(time, tobj);
3974 GetNewTimeval(copy, tcopy);
3975 MEMCPY(tcopy, tobj, struct time_object, 1);
3976
3977 return copy;
3978}
3979
3980static VALUE
3981time_dup(VALUE time)
3982{
3983 VALUE dup = time_s_alloc(rb_obj_class(time));
3984 time_init_copy(dup, time);
3985 return dup;
3986}
3987
3988static VALUE
3989time_localtime(VALUE time)
3990{
3991 struct time_object *tobj;
3992 struct vtm vtm;
3993 VALUE zone;
3994
3995 GetTimeval(time, tobj);
3996 if (TZMODE_LOCALTIME_P(tobj)) {
3997 if (tobj->vtm.tm_got)
3998 return time;
3999 }
4000 else {
4001 time_modify(time);
4002 }
4003
4004 zone = tobj->vtm.zone;
4005 if (maybe_tzobj_p(zone) && zone_localtime(zone, time)) {
4006 return time;
4007 }
4008
4009 if (!localtimew(tobj->timew, &vtm))
4010 rb_raise(rb_eArgError, "localtime error");
4011 tobj->vtm = vtm;
4012
4013 tobj->vtm.tm_got = 1;
4014 TZMODE_SET_LOCALTIME(tobj);
4015 return time;
4016}
4017
4018static VALUE
4019time_zonelocal(VALUE time, VALUE off)
4020{
4021 VALUE zone = off;
4022 if (zone_localtime(zone, time)) return time;
4023
4024 if (NIL_P(off = utc_offset_arg(off))) {
4025 off = zone;
4026 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
4027 if (!zone_localtime(zone, time)) invalid_utc_offset(off);
4028 return time;
4029 }
4030 else if (off == UTC_ZONE) {
4031 return time_gmtime(time);
4032 }
4033 validate_utc_offset(off);
4034
4035 time_set_utc_offset(time, off);
4036 return time_fixoff(time);
4037}
4038
4039/*
4040 * call-seq:
4041 * localtime -> self or new_time
4042 * localtime(zone) -> new_time
4043 *
4044 * With no argument given:
4045 *
4046 * - Returns +self+ if +self+ is a local time.
4047 * - Otherwise returns a new \Time in the user's local timezone:
4048 *
4049 * t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC
4050 * t.localtime # => 2000-01-01 14:15:01 -0600
4051 *
4052 * With argument +zone+ given,
4053 * returns the new \Time object created by converting
4054 * +self+ to the given time zone:
4055 *
4056 * t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC
4057 * t.localtime("-09:00") # => 2000-01-01 11:15:01 -0900
4058 *
4059 * For forms of argument +zone+, see
4060 * {Timezone Specifiers}[rdoc-ref:timezones.rdoc].
4061 *
4062 */
4063
4064static VALUE
4065time_localtime_m(int argc, VALUE *argv, VALUE time)
4066{
4067 VALUE off;
4068
4069 if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
4070 return time_zonelocal(time, off);
4071 }
4072
4073 return time_localtime(time);
4074}
4075
4076/*
4077 * call-seq:
4078 * utc -> self
4079 *
4080 * Returns +self+, converted to the UTC timezone:
4081 *
4082 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4083 * t.utc? # => false
4084 * t.utc # => 2000-01-01 06:00:00 UTC
4085 * t.utc? # => true
4086 *
4087 * Time#gmtime is an alias for Time#utc.
4088 *
4089 * Related: Time#getutc (returns a new converted \Time object).
4090 */
4091
4092static VALUE
4093time_gmtime(VALUE time)
4094{
4095 struct time_object *tobj;
4096 struct vtm vtm;
4097
4098 GetTimeval(time, tobj);
4099 if (TZMODE_UTC_P(tobj)) {
4100 if (tobj->vtm.tm_got)
4101 return time;
4102 }
4103 else {
4104 time_modify(time);
4105 }
4106
4107 vtm.zone = str_utc;
4108 GMTIMEW(tobj->timew, &vtm);
4109 tobj->vtm = vtm;
4110
4111 tobj->vtm.tm_got = 1;
4112 TZMODE_SET_UTC(tobj);
4113 return time;
4114}
4115
4116static VALUE
4117time_fixoff(VALUE time)
4118{
4119 struct time_object *tobj;
4120 struct vtm vtm;
4121 VALUE off, zone;
4122
4123 GetTimeval(time, tobj);
4124 if (TZMODE_FIXOFF_P(tobj)) {
4125 if (tobj->vtm.tm_got)
4126 return time;
4127 }
4128 else {
4129 time_modify(time);
4130 }
4131
4132 if (TZMODE_FIXOFF_P(tobj))
4133 off = tobj->vtm.utc_offset;
4134 else
4135 off = INT2FIX(0);
4136
4137 GMTIMEW(tobj->timew, &vtm);
4138
4139 zone = tobj->vtm.zone;
4140 tobj->vtm = vtm;
4141 tobj->vtm.zone = zone;
4142 vtm_add_offset(&tobj->vtm, off, +1);
4143
4144 tobj->vtm.tm_got = 1;
4145 TZMODE_SET_FIXOFF(tobj, off);
4146 return time;
4147}
4148
4149/*
4150 * call-seq:
4151 * getlocal(zone = nil) -> new_time
4152 *
4153 * Returns a new \Time object representing the value of +self+
4154 * converted to a given timezone;
4155 * if +zone+ is +nil+, the local timezone is used:
4156 *
4157 * t = Time.utc(2000) # => 2000-01-01 00:00:00 UTC
4158 * t.getlocal # => 1999-12-31 18:00:00 -0600
4159 * t.getlocal('+12:00') # => 2000-01-01 12:00:00 +1200
4160 *
4161 * For forms of argument +zone+, see
4162 * {Timezone Specifiers}[rdoc-ref:timezones.rdoc].
4163 *
4164 */
4165
4166static VALUE
4167time_getlocaltime(int argc, VALUE *argv, VALUE time)
4168{
4169 VALUE off;
4170
4171 if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
4172 VALUE zone = off;
4173 if (maybe_tzobj_p(zone)) {
4174 VALUE t = time_dup(time);
4175 if (zone_localtime(off, t)) return t;
4176 }
4177
4178 if (NIL_P(off = utc_offset_arg(off))) {
4179 off = zone;
4180 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
4181 time = time_dup(time);
4182 if (!zone_localtime(zone, time)) invalid_utc_offset(off);
4183 return time;
4184 }
4185 else if (off == UTC_ZONE) {
4186 return time_gmtime(time_dup(time));
4187 }
4188 validate_utc_offset(off);
4189
4190 time = time_dup(time);
4191 time_set_utc_offset(time, off);
4192 return time_fixoff(time);
4193 }
4194
4195 return time_localtime(time_dup(time));
4196}
4197
4198/*
4199 * call-seq:
4200 * getutc -> new_time
4201 *
4202 * Returns a new \Time object representing the value of +self+
4203 * converted to the UTC timezone:
4204 *
4205 * local = Time.local(2000) # => 2000-01-01 00:00:00 -0600
4206 * local.utc? # => false
4207 * utc = local.getutc # => 2000-01-01 06:00:00 UTC
4208 * utc.utc? # => true
4209 * utc == local # => true
4210 *
4211 * Time#getgm is an alias for Time#getutc.
4212 */
4213
4214static VALUE
4215time_getgmtime(VALUE time)
4216{
4217 return time_gmtime(time_dup(time));
4218}
4219
4220static VALUE
4221time_get_tm(VALUE time, struct time_object *tobj)
4222{
4223 if (TZMODE_UTC_P(tobj)) return time_gmtime(time);
4224 if (TZMODE_FIXOFF_P(tobj)) return time_fixoff(time);
4225 return time_localtime(time);
4226}
4227
4228static VALUE strftime_cstr(const char *fmt, size_t len, VALUE time, rb_encoding *enc);
4229#define strftimev(fmt, time, enc) strftime_cstr((fmt), rb_strlen_lit(fmt), (time), (enc))
4230
4231/*
4232 * call-seq:
4233 * ctime -> string
4234 *
4235 * Returns a string representation of +self+,
4236 * formatted by <tt>strftime('%a %b %e %T %Y')</tt>
4237 * or its shorthand version <tt>strftime('%c')</tt>;
4238 * see {Formats for Dates and Times}[rdoc-ref:strftime_formatting.rdoc]:
4239 *
4240 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4241 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4242 * t.strftime('%a %b %e %T %Y') # => "Sun Dec 31 23:59:59 2000"
4243 * t.strftime('%c') # => "Sun Dec 31 23:59:59 2000"
4244 *
4245 * Time#asctime is an alias for Time#ctime.
4246 *
4247 * Related: Time#to_s, Time#inspect:
4248 *
4249 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4250 * t.to_s # => "2000-12-31 23:59:59 +0000"
4251 *
4252 */
4253
4254static VALUE
4255time_asctime(VALUE time)
4256{
4257 return strftimev("%a %b %e %T %Y", time, rb_usascii_encoding());
4258}
4259
4260/*
4261 * call-seq:
4262 * to_s -> string
4263 *
4264 * Returns a string representation of +self+, without subseconds:
4265 *
4266 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4267 * t.to_s # => "2000-12-31 23:59:59 +0000"
4268 *
4269 * Related: Time#ctime, Time#inspect:
4270 *
4271 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4272 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4273 *
4274 */
4275
4276static VALUE
4277time_to_s(VALUE time)
4278{
4279 struct time_object *tobj;
4280
4281 GetTimeval(time, tobj);
4282 if (TZMODE_UTC_P(tobj))
4283 return strftimev("%Y-%m-%d %H:%M:%S UTC", time, rb_usascii_encoding());
4284 else
4285 return strftimev("%Y-%m-%d %H:%M:%S %z", time, rb_usascii_encoding());
4286}
4287
4288/*
4289 * call-seq:
4290 * inspect -> string
4291 *
4292 * Returns a string representation of +self+ with subseconds:
4293 *
4294 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4295 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4296 *
4297 * Related: Time#ctime, Time#to_s:
4298 *
4299 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4300 * t.to_s # => "2000-12-31 23:59:59 +0000"
4301 *
4302 */
4303
4304static VALUE
4305time_inspect(VALUE time)
4306{
4307 struct time_object *tobj;
4308 VALUE str, subsec;
4309
4310 GetTimeval(time, tobj);
4311 str = strftimev("%Y-%m-%d %H:%M:%S", time, rb_usascii_encoding());
4312 subsec = w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE)));
4313 if (subsec == INT2FIX(0)) {
4314 }
4315 else if (FIXNUM_P(subsec) && FIX2LONG(subsec) < TIME_SCALE) {
4316 long len;
4317 rb_str_catf(str, ".%09ld", FIX2LONG(subsec));
4318 for (len=RSTRING_LEN(str); RSTRING_PTR(str)[len-1] == '0' && len > 0; len--)
4319 ;
4320 rb_str_resize(str, len);
4321 }
4322 else {
4323 rb_str_cat_cstr(str, " ");
4324 subsec = quov(subsec, INT2FIX(TIME_SCALE));
4325 rb_str_concat(str, rb_obj_as_string(subsec));
4326 }
4327 if (TZMODE_UTC_P(tobj)) {
4328 rb_str_cat_cstr(str, " UTC");
4329 }
4330 else {
4331 /* ?TODO: subsecond offset */
4332 long off = NUM2LONG(rb_funcall(tobj->vtm.utc_offset, rb_intern("round"), 0));
4333 char sign = (off < 0) ? (off = -off, '-') : '+';
4334 int sec = off % 60;
4335 int min = (off /= 60) % 60;
4336 off /= 60;
4337 rb_str_catf(str, " %c%.2d%.2d", sign, (int)off, min);
4338 if (sec) rb_str_catf(str, "%.2d", sec);
4339 }
4340 return str;
4341}
4342
4343static VALUE
4344time_add0(VALUE klass, const struct time_object *tobj, VALUE torig, VALUE offset, int sign)
4345{
4346 VALUE result;
4347 struct time_object *result_tobj;
4348
4349 offset = num_exact(offset);
4350 if (sign < 0)
4351 result = time_new_timew(klass, wsub(tobj->timew, rb_time_magnify(v2w(offset))));
4352 else
4353 result = time_new_timew(klass, wadd(tobj->timew, rb_time_magnify(v2w(offset))));
4354 GetTimeval(result, result_tobj);
4355 TZMODE_COPY(result_tobj, tobj);
4356
4357 return result;
4358}
4359
4360static VALUE
4361time_add(const struct time_object *tobj, VALUE torig, VALUE offset, int sign)
4362{
4363 return time_add0(rb_cTime, tobj, torig, offset, sign);
4364}
4365
4366/*
4367 * call-seq:
4368 * self + numeric -> new_time
4369 *
4370 * Returns a new \Time object whose value is the sum of the numeric value
4371 * of +self+ and the given +numeric+:
4372 *
4373 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4374 * t + (60 * 60 * 24) # => 2000-01-02 00:00:00 -0600
4375 * t + 0.5 # => 2000-01-01 00:00:00.5 -0600
4376 *
4377 * Related: Time#-.
4378 */
4379
4380static VALUE
4381time_plus(VALUE time1, VALUE time2)
4382{
4383 struct time_object *tobj;
4384 GetTimeval(time1, tobj);
4385
4386 if (IsTimeval(time2)) {
4387 rb_raise(rb_eTypeError, "time + time?");
4388 }
4389 return time_add(tobj, time1, time2, 1);
4390}
4391
4392/*
4393 * call-seq:
4394 * self - numeric -> new_time
4395 * self - other_time -> float
4396 *
4397 * When +numeric+ is given,
4398 * returns a new \Time object whose value is the difference
4399 * of the numeric value of +self+ and +numeric+:
4400 *
4401 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4402 * t - (60 * 60 * 24) # => 1999-12-31 00:00:00 -0600
4403 * t - 0.5 # => 1999-12-31 23:59:59.5 -0600
4404 *
4405 * When +other_time+ is given,
4406 * returns a Float whose value is the difference
4407 * of the numeric values of +self+ and +other_time+:
4408 *
4409 * t - t # => 0.0
4410 *
4411 * Related: Time#+.
4412 */
4413
4414static VALUE
4415time_minus(VALUE time1, VALUE time2)
4416{
4417 struct time_object *tobj;
4418
4419 GetTimeval(time1, tobj);
4420 if (IsTimeval(time2)) {
4421 struct time_object *tobj2;
4422
4423 GetTimeval(time2, tobj2);
4424 return rb_Float(rb_time_unmagnify_to_float(wsub(tobj->timew, tobj2->timew)));
4425 }
4426 return time_add(tobj, time1, time2, -1);
4427}
4428
4429static VALUE
4430ndigits_denominator(VALUE ndigits)
4431{
4432 long nd = NUM2LONG(ndigits);
4433
4434 if (nd < 0) {
4435 rb_raise(rb_eArgError, "negative ndigits given");
4436 }
4437 if (nd == 0) {
4438 return INT2FIX(1);
4439 }
4440 return rb_rational_new(INT2FIX(1),
4441 rb_int_positive_pow(10, (unsigned long)nd));
4442}
4443
4444/*
4445 * call-seq:
4446 * round(ndigits = 0) -> new_time
4447 *
4448 * Returns a new \Time object whose numeric value is that of +self+,
4449 * with its seconds value rounded to precision +ndigits+:
4450 *
4451 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4452 * t # => 2010-03-30 05:43:25.123456789 UTC
4453 * t.round # => 2010-03-30 05:43:25 UTC
4454 * t.round(0) # => 2010-03-30 05:43:25 UTC
4455 * t.round(1) # => 2010-03-30 05:43:25.1 UTC
4456 * t.round(2) # => 2010-03-30 05:43:25.12 UTC
4457 * t.round(3) # => 2010-03-30 05:43:25.123 UTC
4458 * t.round(4) # => 2010-03-30 05:43:25.1235 UTC
4459 *
4460 * t = Time.utc(1999, 12,31, 23, 59, 59)
4461 * t # => 1999-12-31 23:59:59 UTC
4462 * (t + 0.4).round # => 1999-12-31 23:59:59 UTC
4463 * (t + 0.49).round # => 1999-12-31 23:59:59 UTC
4464 * (t + 0.5).round # => 2000-01-01 00:00:00 UTC
4465 * (t + 1.4).round # => 2000-01-01 00:00:00 UTC
4466 * (t + 1.49).round # => 2000-01-01 00:00:00 UTC
4467 * (t + 1.5).round # => 2000-01-01 00:00:01 UTC
4468 *
4469 * Related: Time#ceil, Time#floor.
4470 */
4471
4472static VALUE
4473time_round(int argc, VALUE *argv, VALUE time)
4474{
4475 VALUE ndigits, v, den;
4476 struct time_object *tobj;
4477
4478 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4479 den = INT2FIX(1);
4480 else
4481 den = ndigits_denominator(ndigits);
4482
4483 GetTimeval(time, tobj);
4484 v = w2v(rb_time_unmagnify(tobj->timew));
4485
4486 v = modv(v, den);
4487 if (lt(v, quov(den, INT2FIX(2))))
4488 return time_add(tobj, time, v, -1);
4489 else
4490 return time_add(tobj, time, subv(den, v), 1);
4491}
4492
4493/*
4494 * call-seq:
4495 * floor(ndigits = 0) -> new_time
4496 *
4497 * Returns a new \Time object whose numerical value
4498 * is less than or equal to +self+ with its seconds
4499 * truncated to precision +ndigits+:
4500 *
4501 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4502 * t # => 2010-03-30 05:43:25.123456789 UTC
4503 * t.floor # => 2010-03-30 05:43:25 UTC
4504 * t.floor(2) # => 2010-03-30 05:43:25.12 UTC
4505 * t.floor(4) # => 2010-03-30 05:43:25.1234 UTC
4506 * t.floor(6) # => 2010-03-30 05:43:25.123456 UTC
4507 * t.floor(8) # => 2010-03-30 05:43:25.12345678 UTC
4508 * t.floor(10) # => 2010-03-30 05:43:25.123456789 UTC
4509 *
4510 * t = Time.utc(1999, 12, 31, 23, 59, 59)
4511 * t # => 1999-12-31 23:59:59 UTC
4512 * (t + 0.4).floor # => 1999-12-31 23:59:59 UTC
4513 * (t + 0.9).floor # => 1999-12-31 23:59:59 UTC
4514 * (t + 1.4).floor # => 2000-01-01 00:00:00 UTC
4515 * (t + 1.9).floor # => 2000-01-01 00:00:00 UTC
4516 *
4517 * Related: Time#ceil, Time#round.
4518 */
4519
4520static VALUE
4521time_floor(int argc, VALUE *argv, VALUE time)
4522{
4523 VALUE ndigits, v, den;
4524 struct time_object *tobj;
4525
4526 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4527 den = INT2FIX(1);
4528 else
4529 den = ndigits_denominator(ndigits);
4530
4531 GetTimeval(time, tobj);
4532 v = w2v(rb_time_unmagnify(tobj->timew));
4533
4534 v = modv(v, den);
4535 return time_add(tobj, time, v, -1);
4536}
4537
4538/*
4539 * call-seq:
4540 * ceil(ndigits = 0) -> new_time
4541 *
4542 * Returns a new \Time object whose numerical value
4543 * is greater than or equal to +self+ with its seconds
4544 * truncated to precision +ndigits+:
4545 *
4546 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4547 * t # => 2010-03-30 05:43:25.123456789 UTC
4548 * t.ceil # => 2010-03-30 05:43:26 UTC
4549 * t.ceil(2) # => 2010-03-30 05:43:25.13 UTC
4550 * t.ceil(4) # => 2010-03-30 05:43:25.1235 UTC
4551 * t.ceil(6) # => 2010-03-30 05:43:25.123457 UTC
4552 * t.ceil(8) # => 2010-03-30 05:43:25.12345679 UTC
4553 * t.ceil(10) # => 2010-03-30 05:43:25.123456789 UTC
4554 *
4555 * t = Time.utc(1999, 12, 31, 23, 59, 59)
4556 * t # => 1999-12-31 23:59:59 UTC
4557 * (t + 0.4).ceil # => 2000-01-01 00:00:00 UTC
4558 * (t + 0.9).ceil # => 2000-01-01 00:00:00 UTC
4559 * (t + 1.4).ceil # => 2000-01-01 00:00:01 UTC
4560 * (t + 1.9).ceil # => 2000-01-01 00:00:01 UTC
4561 *
4562 * Related: Time#floor, Time#round.
4563 */
4564
4565static VALUE
4566time_ceil(int argc, VALUE *argv, VALUE time)
4567{
4568 VALUE ndigits, v, den;
4569 struct time_object *tobj;
4570
4571 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4572 den = INT2FIX(1);
4573 else
4574 den = ndigits_denominator(ndigits);
4575
4576 GetTimeval(time, tobj);
4577 v = w2v(rb_time_unmagnify(tobj->timew));
4578
4579 v = modv(v, den);
4580 if (!rb_equal(v, INT2FIX(0))) {
4581 v = subv(den, v);
4582 }
4583 return time_add(tobj, time, v, 1);
4584}
4585
4586/*
4587 * call-seq:
4588 * sec -> integer
4589 *
4590 * Returns the integer second of the minute for +self+,
4591 * in range (0..60):
4592 *
4593 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4594 * # => 2000-01-02 03:04:05 +000006
4595 * t.sec # => 5
4596 *
4597 * Note: the second value may be 60 when there is a
4598 * {leap second}[https://en.wikipedia.org/wiki/Leap_second].
4599 *
4600 * Related: Time#year, Time#mon, Time#min.
4601 */
4602
4603static VALUE
4604time_sec(VALUE time)
4605{
4606 struct time_object *tobj;
4607
4608 GetTimeval(time, tobj);
4609 MAKE_TM(time, tobj);
4610 return INT2FIX(tobj->vtm.sec);
4611}
4612
4613/*
4614 * call-seq:
4615 * min -> integer
4616 *
4617 * Returns the integer minute of the hour for +self+,
4618 * in range (0..59):
4619 *
4620 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4621 * # => 2000-01-02 03:04:05 +000006
4622 * t.min # => 4
4623 *
4624 * Related: Time#year, Time#mon, Time#sec.
4625 */
4626
4627static VALUE
4628time_min(VALUE time)
4629{
4630 struct time_object *tobj;
4631
4632 GetTimeval(time, tobj);
4633 MAKE_TM(time, tobj);
4634 return INT2FIX(tobj->vtm.min);
4635}
4636
4637/*
4638 * call-seq:
4639 * hour -> integer
4640 *
4641 * Returns the integer hour of the day for +self+,
4642 * in range (0..23):
4643 *
4644 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4645 * # => 2000-01-02 03:04:05 +000006
4646 * t.hour # => 3
4647 *
4648 * Related: Time#year, Time#mon, Time#min.
4649 */
4650
4651static VALUE
4652time_hour(VALUE time)
4653{
4654 struct time_object *tobj;
4655
4656 GetTimeval(time, tobj);
4657 MAKE_TM(time, tobj);
4658 return INT2FIX(tobj->vtm.hour);
4659}
4660
4661/*
4662 * call-seq:
4663 * mday -> integer
4664 *
4665 * Returns the integer day of the month for +self+,
4666 * in range (1..31):
4667 *
4668 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4669 * # => 2000-01-02 03:04:05 +000006
4670 * t.mday # => 2
4671 *
4672 * Time#day is an alias for Time#mday.
4673 *
4674 * Related: Time#year, Time#hour, Time#min.
4675 */
4676
4677static VALUE
4678time_mday(VALUE time)
4679{
4680 struct time_object *tobj;
4681
4682 GetTimeval(time, tobj);
4683 MAKE_TM(time, tobj);
4684 return INT2FIX(tobj->vtm.mday);
4685}
4686
4687/*
4688 * call-seq:
4689 * mon -> integer
4690 *
4691 * Returns the integer month of the year for +self+,
4692 * in range (1..12):
4693 *
4694 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4695 * # => 2000-01-02 03:04:05 +000006
4696 * t.mon # => 1
4697 *
4698 * Time#month is an alias for Time#mday.
4699 *
4700 * Related: Time#year, Time#hour, Time#min.
4701 */
4702
4703static VALUE
4704time_mon(VALUE time)
4705{
4706 struct time_object *tobj;
4707
4708 GetTimeval(time, tobj);
4709 MAKE_TM(time, tobj);
4710 return INT2FIX(tobj->vtm.mon);
4711}
4712
4713/*
4714 * call-seq:
4715 * year -> integer
4716 *
4717 * Returns the integer year for +self+:
4718 *
4719 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4720 * # => 2000-01-02 03:04:05 +000006
4721 * t.year # => 2000
4722 *
4723 * Related: Time#mon, Time#hour, Time#min.
4724 */
4725
4726static VALUE
4727time_year(VALUE time)
4728{
4729 struct time_object *tobj;
4730
4731 GetTimeval(time, tobj);
4732 MAKE_TM(time, tobj);
4733 return tobj->vtm.year;
4734}
4735
4736/*
4737 * call-seq:
4738 * wday -> integer
4739 *
4740 * Returns the integer day of the week for +self+,
4741 * in range (0..6), with Sunday as zero.
4742 *
4743 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4744 * # => 2000-01-02 03:04:05 +000006
4745 * t.wday # => 0
4746 * t.sunday? # => true
4747 *
4748 * Related: Time#year, Time#hour, Time#min.
4749 */
4750
4751static VALUE
4752time_wday(VALUE time)
4753{
4754 struct time_object *tobj;
4755
4756 GetTimeval(time, tobj);
4757 MAKE_TM_ENSURE(time, tobj, tobj->vtm.wday != VTM_WDAY_INITVAL);
4758 return INT2FIX((int)tobj->vtm.wday);
4759}
4760
4761#define wday_p(n) {\
4762 return RBOOL(time_wday(time) == INT2FIX(n)); \
4763}
4764
4765/*
4766 * call-seq:
4767 * sunday? -> true or false
4768 *
4769 * Returns +true+ if +self+ represents a Sunday, +false+ otherwise:
4770 *
4771 * t = Time.utc(2000, 1, 2) # => 2000-01-02 00:00:00 UTC
4772 * t.sunday? # => true
4773 *
4774 * Related: Time#monday?, Time#tuesday?, Time#wednesday?.
4775 */
4776
4777static VALUE
4778time_sunday(VALUE time)
4779{
4780 wday_p(0);
4781}
4782
4783/*
4784 * call-seq:
4785 * monday? -> true or false
4786 *
4787 * Returns +true+ if +self+ represents a Monday, +false+ otherwise:
4788 *
4789 * t = Time.utc(2000, 1, 3) # => 2000-01-03 00:00:00 UTC
4790 * t.monday? # => true
4791 *
4792 * Related: Time#tuesday?, Time#wednesday?, Time#thursday?.
4793 */
4794
4795static VALUE
4796time_monday(VALUE time)
4797{
4798 wday_p(1);
4799}
4800
4801/*
4802 * call-seq:
4803 * tuesday? -> true or false
4804 *
4805 * Returns +true+ if +self+ represents a Tuesday, +false+ otherwise:
4806 *
4807 * t = Time.utc(2000, 1, 4) # => 2000-01-04 00:00:00 UTC
4808 * t.tuesday? # => true
4809 *
4810 * Related: Time#wednesday?, Time#thursday?, Time#friday?.
4811 */
4812
4813static VALUE
4814time_tuesday(VALUE time)
4815{
4816 wday_p(2);
4817}
4818
4819/*
4820 * call-seq:
4821 * wednesday? -> true or false
4822 *
4823 * Returns +true+ if +self+ represents a Wednesday, +false+ otherwise:
4824 *
4825 * t = Time.utc(2000, 1, 5) # => 2000-01-05 00:00:00 UTC
4826 * t.wednesday? # => true
4827 *
4828 * Related: Time#thursday?, Time#friday?, Time#saturday?.
4829 */
4830
4831static VALUE
4832time_wednesday(VALUE time)
4833{
4834 wday_p(3);
4835}
4836
4837/*
4838 * call-seq:
4839 * thursday? -> true or false
4840 *
4841 * Returns +true+ if +self+ represents a Thursday, +false+ otherwise:
4842 *
4843 * t = Time.utc(2000, 1, 6) # => 2000-01-06 00:00:00 UTC
4844 * t.thursday? # => true
4845 *
4846 * Related: Time#friday?, Time#saturday?, Time#sunday?.
4847 */
4848
4849static VALUE
4850time_thursday(VALUE time)
4851{
4852 wday_p(4);
4853}
4854
4855/*
4856 * call-seq:
4857 * friday? -> true or false
4858 *
4859 * Returns +true+ if +self+ represents a Friday, +false+ otherwise:
4860 *
4861 * t = Time.utc(2000, 1, 7) # => 2000-01-07 00:00:00 UTC
4862 * t.friday? # => true
4863 *
4864 * Related: Time#saturday?, Time#sunday?, Time#monday?.
4865 */
4866
4867static VALUE
4868time_friday(VALUE time)
4869{
4870 wday_p(5);
4871}
4872
4873/*
4874 * call-seq:
4875 * saturday? -> true or false
4876 *
4877 * Returns +true+ if +self+ represents a Saturday, +false+ otherwise:
4878 *
4879 * t = Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC
4880 * t.saturday? # => true
4881 *
4882 * Related: Time#sunday?, Time#monday?, Time#tuesday?.
4883 */
4884
4885static VALUE
4886time_saturday(VALUE time)
4887{
4888 wday_p(6);
4889}
4890
4891/*
4892 * call-seq:
4893 * yday -> integer
4894 *
4895 * Returns the integer day of the year of +self+, in range (1..366).
4896 *
4897 * Time.new(2000, 1, 1).yday # => 1
4898 * Time.new(2000, 12, 31).yday # => 366
4899 */
4900
4901static VALUE
4902time_yday(VALUE time)
4903{
4904 struct time_object *tobj;
4905
4906 GetTimeval(time, tobj);
4907 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
4908 return INT2FIX(tobj->vtm.yday);
4909}
4910
4911/*
4912 * call-seq:
4913 * dst? -> true or false
4914 *
4915 * Returns +true+ if +self+ is in daylight saving time, +false+ otherwise:
4916 *
4917 * t = Time.local(2000, 1, 1) # => 2000-01-01 00:00:00 -0600
4918 * t.zone # => "Central Standard Time"
4919 * t.dst? # => false
4920 * t = Time.local(2000, 7, 1) # => 2000-07-01 00:00:00 -0500
4921 * t.zone # => "Central Daylight Time"
4922 * t.dst? # => true
4923 *
4924 * Time#isdst is an alias for Time#dst?.
4925 */
4926
4927static VALUE
4928time_isdst(VALUE time)
4929{
4930 struct time_object *tobj;
4931
4932 GetTimeval(time, tobj);
4933 MAKE_TM(time, tobj);
4934 if (tobj->vtm.isdst == VTM_ISDST_INITVAL) {
4935 rb_raise(rb_eRuntimeError, "isdst is not set yet");
4936 }
4937 return RBOOL(tobj->vtm.isdst);
4938}
4939
4940/*
4941 * call-seq:
4942 * time.zone -> string or timezone
4943 *
4944 * Returns the string name of the time zone for +self+:
4945 *
4946 * Time.utc(2000, 1, 1).zone # => "UTC"
4947 * Time.new(2000, 1, 1).zone # => "Central Standard Time"
4948 */
4949
4950static VALUE
4951time_zone(VALUE time)
4952{
4953 struct time_object *tobj;
4954 VALUE zone;
4955
4956 GetTimeval(time, tobj);
4957 MAKE_TM(time, tobj);
4958
4959 if (TZMODE_UTC_P(tobj)) {
4960 return rb_usascii_str_new_cstr("UTC");
4961 }
4962 zone = tobj->vtm.zone;
4963 if (NIL_P(zone))
4964 return Qnil;
4965
4966 if (RB_TYPE_P(zone, T_STRING))
4967 zone = rb_str_dup(zone);
4968 return zone;
4969}
4970
4971/*
4972 * call-seq:
4973 * utc_offset -> integer
4974 *
4975 * Returns the offset in seconds between the timezones of UTC and +self+:
4976 *
4977 * Time.utc(2000, 1, 1).utc_offset # => 0
4978 * Time.local(2000, 1, 1).utc_offset # => -21600 # -6*3600, or minus six hours.
4979 *
4980 * Time#gmt_offset and Time#gmtoff are aliases for Time#utc_offset.
4981 */
4982
4983VALUE
4985{
4986 struct time_object *tobj;
4987
4988 GetTimeval(time, tobj);
4989
4990 if (TZMODE_UTC_P(tobj)) {
4991 return INT2FIX(0);
4992 }
4993 else {
4994 MAKE_TM(time, tobj);
4995 return tobj->vtm.utc_offset;
4996 }
4997}
4998
4999/*
5000 * call-seq:
5001 * to_a -> array
5002 *
5003 * Returns a 10-element array of values representing +self+:
5004 *
5005 * Time.utc(2000, 1, 1).to_a
5006 * # => [0, 0, 0, 1, 1, 2000, 6, 1, false, "UTC"]
5007 * # [sec, min, hour, day, mon, year, wday, yday, dst?, zone]
5008 *
5009 * The returned array is suitable for use as an argument to Time.utc or Time.local
5010 * to create a new \Time object.
5011 *
5012 */
5013
5014static VALUE
5015time_to_a(VALUE time)
5016{
5017 struct time_object *tobj;
5018
5019 GetTimeval(time, tobj);
5020 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5021 return rb_ary_new3(10,
5022 INT2FIX(tobj->vtm.sec),
5023 INT2FIX(tobj->vtm.min),
5024 INT2FIX(tobj->vtm.hour),
5025 INT2FIX(tobj->vtm.mday),
5026 INT2FIX(tobj->vtm.mon),
5027 tobj->vtm.year,
5028 INT2FIX(tobj->vtm.wday),
5029 INT2FIX(tobj->vtm.yday),
5030 RBOOL(tobj->vtm.isdst),
5031 time_zone(time));
5032}
5033
5034/*
5035 * call-seq:
5036 * deconstruct_keys(array_of_names_or_nil) -> hash
5037 *
5038 * Returns a hash of the name/value pairs, to use in pattern matching.
5039 * Possible keys are: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>,
5040 * <tt>:yday</tt>, <tt>:wday</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>,
5041 * <tt>:subsec</tt>, <tt>:dst</tt>, <tt>:zone</tt>.
5042 *
5043 * Possible usages:
5044 *
5045 * t = Time.utc(2022, 10, 5, 21, 25, 30)
5046 *
5047 * if t in wday: 3, day: ..7 # uses deconstruct_keys underneath
5048 * puts "first Wednesday of the month"
5049 * end
5050 * #=> prints "first Wednesday of the month"
5051 *
5052 * case t
5053 * in year: ...2022
5054 * puts "too old"
5055 * in month: ..9
5056 * puts "quarter 1-3"
5057 * in wday: 1..5, month:
5058 * puts "working day in month #{month}"
5059 * end
5060 * #=> prints "working day in month 10"
5061 *
5062 * Note that deconstruction by pattern can also be combined with class check:
5063 *
5064 * if t in Time(wday: 3, day: ..7)
5065 * puts "first Wednesday of the month"
5066 * end
5067 *
5068 */
5069static VALUE
5070time_deconstruct_keys(VALUE time, VALUE keys)
5071{
5072 struct time_object *tobj;
5073 VALUE h;
5074 long i;
5075
5076 GetTimeval(time, tobj);
5077 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5078
5079 if (NIL_P(keys)) {
5080 h = rb_hash_new_with_size(11);
5081
5082 rb_hash_aset(h, sym_year, tobj->vtm.year);
5083 rb_hash_aset(h, sym_month, INT2FIX(tobj->vtm.mon));
5084 rb_hash_aset(h, sym_day, INT2FIX(tobj->vtm.mday));
5085 rb_hash_aset(h, sym_yday, INT2FIX(tobj->vtm.yday));
5086 rb_hash_aset(h, sym_wday, INT2FIX(tobj->vtm.wday));
5087 rb_hash_aset(h, sym_hour, INT2FIX(tobj->vtm.hour));
5088 rb_hash_aset(h, sym_min, INT2FIX(tobj->vtm.min));
5089 rb_hash_aset(h, sym_sec, INT2FIX(tobj->vtm.sec));
5090 rb_hash_aset(h, sym_subsec,
5091 quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
5092 rb_hash_aset(h, sym_dst, RBOOL(tobj->vtm.isdst));
5093 rb_hash_aset(h, sym_zone, time_zone(time));
5094
5095 return h;
5096 }
5097 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
5099 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
5100 rb_obj_class(keys));
5101
5102 }
5103
5104 h = rb_hash_new_with_size(RARRAY_LEN(keys));
5105
5106 for (i=0; i<RARRAY_LEN(keys); i++) {
5107 VALUE key = RARRAY_AREF(keys, i);
5108
5109 if (sym_year == key) rb_hash_aset(h, key, tobj->vtm.year);
5110 if (sym_month == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mon));
5111 if (sym_day == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mday));
5112 if (sym_yday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.yday));
5113 if (sym_wday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.wday));
5114 if (sym_hour == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.hour));
5115 if (sym_min == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.min));
5116 if (sym_sec == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.sec));
5117 if (sym_subsec == key) {
5118 rb_hash_aset(h, key, quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
5119 }
5120 if (sym_dst == key) rb_hash_aset(h, key, RBOOL(tobj->vtm.isdst));
5121 if (sym_zone == key) rb_hash_aset(h, key, time_zone(time));
5122 }
5123 return h;
5124}
5125
5126static VALUE
5127rb_strftime_alloc(const char *format, size_t format_len, rb_encoding *enc,
5128 VALUE time, struct vtm *vtm, wideval_t timew, int gmt)
5129{
5130 VALUE timev = Qnil;
5131 struct timespec ts;
5132
5133 if (!timew2timespec_exact(timew, &ts))
5134 timev = w2v(rb_time_unmagnify(timew));
5135
5136 if (NIL_P(timev)) {
5137 return rb_strftime_timespec(format, format_len, enc, time, vtm, &ts, gmt);
5138 }
5139 else {
5140 return rb_strftime(format, format_len, enc, time, vtm, timev, gmt);
5141 }
5142}
5143
5144static VALUE
5145strftime_cstr(const char *fmt, size_t len, VALUE time, rb_encoding *enc)
5146{
5147 struct time_object *tobj;
5148 VALUE str;
5149
5150 GetTimeval(time, tobj);
5151 MAKE_TM(time, tobj);
5152 str = rb_strftime_alloc(fmt, len, enc, time, &tobj->vtm, tobj->timew, TZMODE_UTC_P(tobj));
5153 if (!str) rb_raise(rb_eArgError, "invalid format: %s", fmt);
5154 return str;
5155}
5156
5157/*
5158 * call-seq:
5159 * strftime(format_string) -> string
5160 *
5161 * Returns a string representation of +self+,
5162 * formatted according to the given string +format+.
5163 * See {Formats for Dates and Times}[rdoc-ref:strftime_formatting.rdoc].
5164 */
5165
5166static VALUE
5167time_strftime(VALUE time, VALUE format)
5168{
5169 struct time_object *tobj;
5170 const char *fmt;
5171 long len;
5172 rb_encoding *enc;
5173 VALUE tmp;
5174
5175 GetTimeval(time, tobj);
5176 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5177 StringValue(format);
5178 if (!rb_enc_str_asciicompat_p(format)) {
5179 rb_raise(rb_eArgError, "format should have ASCII compatible encoding");
5180 }
5181 tmp = rb_str_tmp_frozen_acquire(format);
5182 fmt = RSTRING_PTR(tmp);
5183 len = RSTRING_LEN(tmp);
5184 enc = rb_enc_get(format);
5185 if (len == 0) {
5186 rb_warning("strftime called with empty format string");
5187 return rb_enc_str_new(0, 0, enc);
5188 }
5189 else {
5190 VALUE str = rb_strftime_alloc(fmt, len, enc, time, &tobj->vtm, tobj->timew,
5191 TZMODE_UTC_P(tobj));
5192 rb_str_tmp_frozen_release(format, tmp);
5193 if (!str) rb_raise(rb_eArgError, "invalid format: %"PRIsVALUE, format);
5194 return str;
5195 }
5196}
5197
5198int ruby_marshal_write_long(long x, char *buf);
5199
5200enum {base_dump_size = 8};
5201
5202/* :nodoc: */
5203static VALUE
5204time_mdump(VALUE time)
5205{
5206 struct time_object *tobj;
5207 unsigned long p, s;
5208 char buf[base_dump_size + sizeof(long) + 1];
5209 int i;
5210 VALUE str;
5211
5212 struct vtm vtm;
5213 long year;
5214 long usec, nsec;
5215 VALUE subsecx, nano, subnano, v, zone;
5216
5217 VALUE year_extend = Qnil;
5218 const int max_year = 1900+0xffff;
5219
5220 GetTimeval(time, tobj);
5221
5222 gmtimew(tobj->timew, &vtm);
5223
5224 if (FIXNUM_P(vtm.year)) {
5225 year = FIX2LONG(vtm.year);
5226 if (year > max_year) {
5227 year_extend = INT2FIX(year - max_year);
5228 year = max_year;
5229 }
5230 else if (year < 1900) {
5231 year_extend = LONG2NUM(1900 - year);
5232 year = 1900;
5233 }
5234 }
5235 else {
5236 if (rb_int_positive_p(vtm.year)) {
5237 year_extend = rb_int_minus(vtm.year, INT2FIX(max_year));
5238 year = max_year;
5239 }
5240 else {
5241 year_extend = rb_int_minus(INT2FIX(1900), vtm.year);
5242 year = 1900;
5243 }
5244 }
5245
5246 subsecx = vtm.subsecx;
5247
5248 nano = mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE));
5249 divmodv(nano, INT2FIX(1), &v, &subnano);
5250 nsec = FIX2LONG(v);
5251 usec = nsec / 1000;
5252 nsec = nsec % 1000;
5253
5254 nano = addv(LONG2FIX(nsec), subnano);
5255
5256 p = 0x1UL << 31 | /* 1 */
5257 TZMODE_UTC_P(tobj) << 30 | /* 1 */
5258 (year-1900) << 14 | /* 16 */
5259 (vtm.mon-1) << 10 | /* 4 */
5260 vtm.mday << 5 | /* 5 */
5261 vtm.hour; /* 5 */
5262 s = (unsigned long)vtm.min << 26 | /* 6 */
5263 vtm.sec << 20 | /* 6 */
5264 usec; /* 20 */
5265
5266 for (i=0; i<4; i++) {
5267 buf[i] = (unsigned char)p;
5268 p = RSHIFT(p, 8);
5269 }
5270 for (i=4; i<8; i++) {
5271 buf[i] = (unsigned char)s;
5272 s = RSHIFT(s, 8);
5273 }
5274
5275 if (!NIL_P(year_extend)) {
5276 /*
5277 * Append extended year distance from 1900..(1900+0xffff). In
5278 * each cases, there is no sign as the value is positive. The
5279 * format is length (marshaled long) + little endian packed
5280 * binary (like as Integer).
5281 */
5282 size_t ysize = rb_absint_size(year_extend, NULL);
5283 char *p, *const buf_year_extend = buf + base_dump_size;
5284 if (ysize > LONG_MAX ||
5285 (i = ruby_marshal_write_long((long)ysize, buf_year_extend)) < 0) {
5286 rb_raise(rb_eArgError, "year too %s to marshal: %"PRIsVALUE" UTC",
5287 (year == 1900 ? "small" : "big"), vtm.year);
5288 }
5289 i += base_dump_size;
5290 str = rb_str_new(NULL, i + ysize);
5291 p = RSTRING_PTR(str);
5292 memcpy(p, buf, i);
5293 p += i;
5294 rb_integer_pack(year_extend, p, ysize, 1, 0, INTEGER_PACK_LITTLE_ENDIAN);
5295 }
5296 else {
5297 str = rb_str_new(buf, base_dump_size);
5298 }
5299 rb_copy_generic_ivar(str, time);
5300 if (!rb_equal(nano, INT2FIX(0))) {
5301 if (RB_TYPE_P(nano, T_RATIONAL)) {
5302 rb_ivar_set(str, id_nano_num, RRATIONAL(nano)->num);
5303 rb_ivar_set(str, id_nano_den, RRATIONAL(nano)->den);
5304 }
5305 else {
5306 rb_ivar_set(str, id_nano_num, nano);
5307 rb_ivar_set(str, id_nano_den, INT2FIX(1));
5308 }
5309 }
5310 if (nsec) { /* submicro is only for Ruby 1.9.1 compatibility */
5311 /*
5312 * submicro is formatted in fixed-point packed BCD (without sign).
5313 * It represent digits under microsecond.
5314 * For nanosecond resolution, 3 digits (2 bytes) are used.
5315 * However it can be longer.
5316 * Extra digits are ignored for loading.
5317 */
5318 char buf[2];
5319 int len = (int)sizeof(buf);
5320 buf[1] = (char)((nsec % 10) << 4);
5321 nsec /= 10;
5322 buf[0] = (char)(nsec % 10);
5323 nsec /= 10;
5324 buf[0] |= (char)((nsec % 10) << 4);
5325 if (buf[1] == 0)
5326 len = 1;
5327 rb_ivar_set(str, id_submicro, rb_str_new(buf, len));
5328 }
5329 if (!TZMODE_UTC_P(tobj)) {
5330 VALUE off = rb_time_utc_offset(time), div, mod;
5331 divmodv(off, INT2FIX(1), &div, &mod);
5332 if (rb_equal(mod, INT2FIX(0)))
5333 off = rb_Integer(div);
5334 rb_ivar_set(str, id_offset, off);
5335 }
5336 zone = tobj->vtm.zone;
5337 if (maybe_tzobj_p(zone)) {
5338 zone = rb_funcallv(zone, id_name, 0, 0);
5339 }
5340 rb_ivar_set(str, id_zone, zone);
5341 return str;
5342}
5343
5344/* :nodoc: */
5345static VALUE
5346time_dump(int argc, VALUE *argv, VALUE time)
5347{
5348 VALUE str;
5349
5350 rb_check_arity(argc, 0, 1);
5351 str = time_mdump(time);
5352
5353 return str;
5354}
5355
5356static VALUE
5357mload_findzone(VALUE arg)
5358{
5359 VALUE *argp = (VALUE *)arg;
5360 VALUE time = argp[0], zone = argp[1];
5361 return find_timezone(time, zone);
5362}
5363
5364static VALUE
5365mload_zone(VALUE time, VALUE zone)
5366{
5367 VALUE z, args[2];
5368 args[0] = time;
5369 args[1] = zone;
5370 z = rb_rescue(mload_findzone, (VALUE)args, 0, Qnil);
5371 if (NIL_P(z)) return rb_fstring(zone);
5372 if (RB_TYPE_P(z, T_STRING)) return rb_fstring(z);
5373 return z;
5374}
5375
5376long ruby_marshal_read_long(const char **buf, long len);
5377
5378/* :nodoc: */
5379static VALUE
5380time_mload(VALUE time, VALUE str)
5381{
5382 struct time_object *tobj;
5383 unsigned long p, s;
5384 time_t sec;
5385 long usec;
5386 unsigned char *buf;
5387 struct vtm vtm;
5388 int i, gmt;
5389 long nsec;
5390 VALUE submicro, nano_num, nano_den, offset, zone, year;
5391 wideval_t timew;
5392
5393 time_modify(time);
5394
5395#define get_attr(attr, iffound) \
5396 attr = rb_attr_delete(str, id_##attr); \
5397 if (!NIL_P(attr)) { \
5398 iffound; \
5399 }
5400
5401 get_attr(nano_num, {});
5402 get_attr(nano_den, {});
5403 get_attr(submicro, {});
5404 get_attr(offset, (offset = rb_rescue(validate_utc_offset, offset, 0, Qnil)));
5405 get_attr(zone, (zone = rb_rescue(validate_zone_name, zone, 0, Qnil)));
5406 get_attr(year, {});
5407
5408#undef get_attr
5409
5410 rb_copy_generic_ivar(time, str);
5411
5412 StringValue(str);
5413 buf = (unsigned char *)RSTRING_PTR(str);
5414 if (RSTRING_LEN(str) < base_dump_size) {
5415 goto invalid_format;
5416 }
5417
5418 p = s = 0;
5419 for (i=0; i<4; i++) {
5420 p |= (unsigned long)buf[i]<<(8*i);
5421 }
5422 for (i=4; i<8; i++) {
5423 s |= (unsigned long)buf[i]<<(8*(i-4));
5424 }
5425
5426 if ((p & (1UL<<31)) == 0) {
5427 gmt = 0;
5428 offset = Qnil;
5429 sec = p;
5430 usec = s;
5431 nsec = usec * 1000;
5432 timew = wadd(rb_time_magnify(TIMET2WV(sec)), wmulquoll(WINT2FIXWV(usec), TIME_SCALE, 1000000));
5433 }
5434 else {
5435 p &= ~(1UL<<31);
5436 gmt = (int)((p >> 30) & 0x1);
5437
5438 if (NIL_P(year)) {
5439 year = INT2FIX(((int)(p >> 14) & 0xffff) + 1900);
5440 }
5441 if (RSTRING_LEN(str) > base_dump_size) {
5442 long len = RSTRING_LEN(str) - base_dump_size;
5443 long ysize = 0;
5444 VALUE year_extend;
5445 const char *ybuf = (const char *)(buf += base_dump_size);
5446 ysize = ruby_marshal_read_long(&ybuf, len);
5447 len -= ybuf - (const char *)buf;
5448 if (ysize < 0 || ysize > len) goto invalid_format;
5449 year_extend = rb_integer_unpack(ybuf, ysize, 1, 0, INTEGER_PACK_LITTLE_ENDIAN);
5450 if (year == INT2FIX(1900)) {
5451 year = rb_int_minus(year, year_extend);
5452 }
5453 else {
5454 year = rb_int_plus(year, year_extend);
5455 }
5456 }
5457 unsigned int mon = ((int)(p >> 10) & 0xf); /* 0...12 */
5458 if (mon >= 12) {
5459 mon -= 12;
5460 year = addv(year, LONG2FIX(1));
5461 }
5462 vtm.year = year;
5463 vtm.mon = mon + 1;
5464 vtm.mday = (int)(p >> 5) & 0x1f;
5465 vtm.hour = (int) p & 0x1f;
5466 vtm.min = (int)(s >> 26) & 0x3f;
5467 vtm.sec = (int)(s >> 20) & 0x3f;
5468 vtm.utc_offset = INT2FIX(0);
5469 vtm.yday = vtm.wday = 0;
5470 vtm.isdst = 0;
5471 vtm.zone = str_empty;
5472
5473 usec = (long)(s & 0xfffff);
5474 nsec = usec * 1000;
5475
5476
5477 vtm.subsecx = mulquov(LONG2FIX(nsec), INT2FIX(TIME_SCALE), LONG2FIX(1000000000));
5478 if (nano_num != Qnil) {
5479 VALUE nano = quov(num_exact(nano_num), num_exact(nano_den));
5480 vtm.subsecx = addv(vtm.subsecx, mulquov(nano, INT2FIX(TIME_SCALE), LONG2FIX(1000000000)));
5481 }
5482 else if (submicro != Qnil) { /* for Ruby 1.9.1 compatibility */
5483 unsigned char *ptr;
5484 long len;
5485 int digit;
5486 ptr = (unsigned char*)StringValuePtr(submicro);
5487 len = RSTRING_LEN(submicro);
5488 nsec = 0;
5489 if (0 < len) {
5490 if (10 <= (digit = ptr[0] >> 4)) goto end_submicro;
5491 nsec += digit * 100;
5492 if (10 <= (digit = ptr[0] & 0xf)) goto end_submicro;
5493 nsec += digit * 10;
5494 }
5495 if (1 < len) {
5496 if (10 <= (digit = ptr[1] >> 4)) goto end_submicro;
5497 nsec += digit;
5498 }
5499 vtm.subsecx = addv(vtm.subsecx, mulquov(LONG2FIX(nsec), INT2FIX(TIME_SCALE), LONG2FIX(1000000000)));
5500end_submicro: ;
5501 }
5502 timew = timegmw(&vtm);
5503 }
5504
5505 GetNewTimeval(time, tobj);
5506 TZMODE_SET_LOCALTIME(tobj);
5507 tobj->vtm.tm_got = 0;
5508 tobj->timew = timew;
5509
5510 if (gmt) {
5511 TZMODE_SET_UTC(tobj);
5512 }
5513 else if (!NIL_P(offset)) {
5514 time_set_utc_offset(time, offset);
5515 time_fixoff(time);
5516 }
5517 if (!NIL_P(zone)) {
5518 zone = mload_zone(time, zone);
5519 tobj->vtm.zone = zone;
5520 zone_localtime(zone, time);
5521 }
5522
5523 return time;
5524
5525 invalid_format:
5526 rb_raise(rb_eTypeError, "marshaled time format differ");
5528}
5529
5530/* :nodoc: */
5531static VALUE
5532time_load(VALUE klass, VALUE str)
5533{
5534 VALUE time = time_s_alloc(klass);
5535
5536 time_mload(time, str);
5537 return time;
5538}
5539
5540/* :nodoc:*/
5541/* Document-class: Time::tm
5542 *
5543 * A container class for timezone conversion.
5544 */
5545
5546/*
5547 * call-seq:
5548 *
5549 * Time::tm.from_time(t) -> tm
5550 *
5551 * Creates new Time::tm object from a Time object.
5552 */
5553
5554static VALUE
5555tm_from_time(VALUE klass, VALUE time)
5556{
5557 struct time_object *tobj;
5558 struct vtm vtm, *v;
5559#if TM_IS_TIME
5560 VALUE tm;
5561 struct time_object *ttm;
5562
5563 GetTimeval(time, tobj);
5564 tm = time_s_alloc(klass);
5565 ttm = DATA_PTR(tm);
5566 v = &vtm;
5567 GMTIMEW(ttm->timew = tobj->timew, v);
5568 ttm->timew = wsub(ttm->timew, v->subsecx);
5569 v->subsecx = INT2FIX(0);
5570 v->zone = Qnil;
5571 ttm->vtm = *v;
5572
5573 ttm->vtm.tm_got = 1;
5574 TZMODE_SET_UTC(ttm);
5575 return tm;
5576#else
5577 VALUE args[8];
5578 int i = 0;
5579
5580 GetTimeval(time, tobj);
5581 if (tobj->tm_got && TZMODE_UTC_P(tobj))
5582 v = &tobj->vtm;
5583 else
5584 GMTIMEW(tobj->timew, v = &vtm);
5585 args[i++] = v->year;
5586 args[i++] = INT2FIX(v->mon);
5587 args[i++] = INT2FIX(v->mday);
5588 args[i++] = INT2FIX(v->hour);
5589 args[i++] = INT2FIX(v->min);
5590 args[i++] = INT2FIX(v->sec);
5591 switch (v->isdst) {
5592 case 0: args[i++] = Qfalse; break;
5593 case 1: args[i++] = Qtrue; break;
5594 default: args[i++] = Qnil; break;
5595 }
5596 args[i++] = w2v(rb_time_unmagnify(tobj->timew));
5597 return rb_class_new_instance(i, args, klass);
5598#endif
5599}
5600
5601/*
5602 * call-seq:
5603 *
5604 * Time::tm.new(year, month=nil, day=nil, hour=nil, min=nil, sec=nil, zone=nil) -> tm
5605 *
5606 * Creates new Time::tm object.
5607 */
5608
5609static VALUE
5610tm_initialize(int argc, VALUE *argv, VALUE tm)
5611{
5612 struct vtm vtm;
5613 wideval_t t;
5614
5615 if (rb_check_arity(argc, 1, 7) > 6) argc = 6;
5616 time_arg(argc, argv, &vtm);
5617 t = timegmw(&vtm);
5618 {
5619#if TM_IS_TIME
5620 struct time_object *tobj = DATA_PTR(tm);
5621 TZMODE_SET_UTC(tobj);
5622 tobj->timew = t;
5623 tobj->vtm = vtm;
5624#else
5625 int i = 0;
5626 RSTRUCT_SET(tm, i++, INT2FIX(vtm.sec));
5627 RSTRUCT_SET(tm, i++, INT2FIX(vtm.min));
5628 RSTRUCT_SET(tm, i++, INT2FIX(vtm.hour));
5629 RSTRUCT_SET(tm, i++, INT2FIX(vtm.mday));
5630 RSTRUCT_SET(tm, i++, INT2FIX(vtm.mon));
5631 RSTRUCT_SET(tm, i++, vtm.year);
5632 RSTRUCT_SET(tm, i++, w2v(rb_time_unmagnify(t)));
5633#endif
5634 }
5635 return tm;
5636}
5637
5638/* call-seq:
5639 *
5640 * tm.to_time -> time
5641 *
5642 * Returns a new Time object.
5643 */
5644
5645static VALUE
5646tm_to_time(VALUE tm)
5647{
5648#if TM_IS_TIME
5649 struct time_object *torig = get_timeval(tm);
5650 VALUE dup = time_s_alloc(rb_cTime);
5651 struct time_object *tobj = DATA_PTR(dup);
5652 *tobj = *torig;
5653 return dup;
5654#else
5655 VALUE t[6];
5656 const VALUE *p = RSTRUCT_CONST_PTR(tm);
5657 int i;
5658
5659 for (i = 0; i < numberof(t); ++i) {
5660 t[i] = p[numberof(t) - 1 - i];
5661 }
5662 return time_s_mkutc(numberof(t), t, rb_cTime);
5663#endif
5664}
5665
5666#if !TM_IS_TIME
5667static VALUE
5668tm_zero(VALUE tm)
5669{
5670 return INT2FIX(0);
5671}
5672
5673#define tm_subsec tm_zero
5674#define tm_utc_offset tm_zero
5675
5676static VALUE
5677tm_isdst(VALUE tm)
5678{
5679 return Qfalse;
5680}
5681
5682static VALUE
5683tm_to_s(VALUE tm)
5684{
5685 const VALUE *p = RSTRUCT_CONST_PTR(tm);
5686
5687 return rb_sprintf("%.4"PRIsVALUE"-%.2"PRIsVALUE"-%.2"PRIsVALUE" "
5688 "%.2"PRIsVALUE":%.2"PRIsVALUE":%.2"PRIsVALUE" "
5689 "UTC",
5690 p[5], p[4], p[3], p[2], p[1], p[0]);
5691}
5692#else
5693static VALUE
5694tm_plus(VALUE tm, VALUE offset)
5695{
5696 return time_add0(rb_obj_class(tm), get_timeval(tm), tm, offset, +1);
5697}
5698
5699static VALUE
5700tm_minus(VALUE tm, VALUE offset)
5701{
5702 return time_add0(rb_obj_class(tm), get_timeval(tm), tm, offset, -1);
5703}
5704#endif
5705
5706static VALUE
5707Init_tm(VALUE outer, const char *name)
5708{
5709 /* :stopdoc:*/
5710 VALUE tm;
5711#if TM_IS_TIME
5712 tm = rb_define_class_under(outer, name, rb_cObject);
5713 rb_define_alloc_func(tm, time_s_alloc);
5714 rb_define_method(tm, "sec", time_sec, 0);
5715 rb_define_method(tm, "min", time_min, 0);
5716 rb_define_method(tm, "hour", time_hour, 0);
5717 rb_define_method(tm, "mday", time_mday, 0);
5718 rb_define_method(tm, "day", time_mday, 0);
5719 rb_define_method(tm, "mon", time_mon, 0);
5720 rb_define_method(tm, "month", time_mon, 0);
5721 rb_define_method(tm, "year", time_year, 0);
5722 rb_define_method(tm, "isdst", time_isdst, 0);
5723 rb_define_method(tm, "dst?", time_isdst, 0);
5724 rb_define_method(tm, "zone", time_zone, 0);
5725 rb_define_method(tm, "gmtoff", rb_time_utc_offset, 0);
5726 rb_define_method(tm, "gmt_offset", rb_time_utc_offset, 0);
5727 rb_define_method(tm, "utc_offset", rb_time_utc_offset, 0);
5728 rb_define_method(tm, "utc?", time_utc_p, 0);
5729 rb_define_method(tm, "gmt?", time_utc_p, 0);
5730 rb_define_method(tm, "to_s", time_to_s, 0);
5731 rb_define_method(tm, "inspect", time_inspect, 0);
5732 rb_define_method(tm, "to_a", time_to_a, 0);
5733 rb_define_method(tm, "tv_sec", time_to_i, 0);
5734 rb_define_method(tm, "tv_usec", time_usec, 0);
5735 rb_define_method(tm, "usec", time_usec, 0);
5736 rb_define_method(tm, "tv_nsec", time_nsec, 0);
5737 rb_define_method(tm, "nsec", time_nsec, 0);
5738 rb_define_method(tm, "subsec", time_subsec, 0);
5739 rb_define_method(tm, "to_i", time_to_i, 0);
5740 rb_define_method(tm, "to_f", time_to_f, 0);
5741 rb_define_method(tm, "to_r", time_to_r, 0);
5742 rb_define_method(tm, "+", tm_plus, 1);
5743 rb_define_method(tm, "-", tm_minus, 1);
5744#else
5745 tm = rb_struct_define_under(outer, "tm",
5746 "sec", "min", "hour",
5747 "mday", "mon", "year",
5748 "to_i", NULL);
5749 rb_define_method(tm, "subsec", tm_subsec, 0);
5750 rb_define_method(tm, "utc_offset", tm_utc_offset, 0);
5751 rb_define_method(tm, "to_s", tm_to_s, 0);
5752 rb_define_method(tm, "inspect", tm_to_s, 0);
5753 rb_define_method(tm, "isdst", tm_isdst, 0);
5754 rb_define_method(tm, "dst?", tm_isdst, 0);
5755#endif
5756 rb_define_method(tm, "initialize", tm_initialize, -1);
5757 rb_define_method(tm, "utc", tm_to_time, 0);
5758 rb_alias(tm, rb_intern_const("to_time"), rb_intern_const("utc"));
5759 rb_define_singleton_method(tm, "from_time", tm_from_time, 1);
5760 /* :startdoc:*/
5761
5762 return tm;
5763}
5764
5765VALUE
5766rb_time_zone_abbreviation(VALUE zone, VALUE time)
5767{
5768 VALUE tm, abbr, strftime_args[2];
5769
5770 abbr = rb_check_string_type(zone);
5771 if (!NIL_P(abbr)) return abbr;
5772
5773 tm = tm_from_time(rb_cTimeTM, time);
5774 abbr = rb_check_funcall(zone, rb_intern("abbr"), 1, &tm);
5775 if (!UNDEF_P(abbr)) {
5776 goto found;
5777 }
5778#ifdef SUPPORT_TZINFO_ZONE_ABBREVIATION
5779 abbr = rb_check_funcall(zone, rb_intern("period_for_utc"), 1, &tm);
5780 if (!UNDEF_P(abbr)) {
5781 abbr = rb_funcallv(abbr, rb_intern("abbreviation"), 0, 0);
5782 goto found;
5783 }
5784#endif
5785 strftime_args[0] = rb_fstring_lit("%Z");
5786 strftime_args[1] = tm;
5787 abbr = rb_check_funcall(zone, rb_intern("strftime"), 2, strftime_args);
5788 if (!UNDEF_P(abbr)) {
5789 goto found;
5790 }
5791 abbr = rb_check_funcall_default(zone, idName, 0, 0, Qnil);
5792 found:
5793 return rb_obj_as_string(abbr);
5794}
5795
5796/* Internal Details:
5797 *
5798 * Since Ruby 1.9.2, Time implementation uses a signed 63 bit integer or
5799 * Integer(T_BIGNUM), Rational.
5800 * The integer is a number of nanoseconds since the _Epoch_ which can
5801 * represent 1823-11-12 to 2116-02-20.
5802 * When Integer(T_BIGNUM) or Rational is used (before 1823, after 2116, under
5803 * nanosecond), Time works slower than when integer is used.
5804 */
5805
5806//
5807void
5808Init_Time(void)
5809{
5810 id_submicro = rb_intern_const("submicro");
5811 id_nano_num = rb_intern_const("nano_num");
5812 id_nano_den = rb_intern_const("nano_den");
5813 id_offset = rb_intern_const("offset");
5814 id_zone = rb_intern_const("zone");
5815 id_nanosecond = rb_intern_const("nanosecond");
5816 id_microsecond = rb_intern_const("microsecond");
5817 id_millisecond = rb_intern_const("millisecond");
5818 id_nsec = rb_intern_const("nsec");
5819 id_usec = rb_intern_const("usec");
5820 id_local_to_utc = rb_intern_const("local_to_utc");
5821 id_utc_to_local = rb_intern_const("utc_to_local");
5822 id_year = rb_intern_const("year");
5823 id_mon = rb_intern_const("mon");
5824 id_mday = rb_intern_const("mday");
5825 id_hour = rb_intern_const("hour");
5826 id_min = rb_intern_const("min");
5827 id_sec = rb_intern_const("sec");
5828 id_isdst = rb_intern_const("isdst");
5829 id_find_timezone = rb_intern_const("find_timezone");
5830
5831 sym_year = ID2SYM(rb_intern_const("year"));
5832 sym_month = ID2SYM(rb_intern_const("month"));
5833 sym_yday = ID2SYM(rb_intern_const("yday"));
5834 sym_wday = ID2SYM(rb_intern_const("wday"));
5835 sym_day = ID2SYM(rb_intern_const("day"));
5836 sym_hour = ID2SYM(rb_intern_const("hour"));
5837 sym_min = ID2SYM(rb_intern_const("min"));
5838 sym_sec = ID2SYM(rb_intern_const("sec"));
5839 sym_subsec = ID2SYM(rb_intern_const("subsec"));
5840 sym_dst = ID2SYM(rb_intern_const("dst"));
5841 sym_zone = ID2SYM(rb_intern_const("zone"));
5842
5843 str_utc = rb_fstring_lit("UTC");
5844 rb_gc_register_mark_object(str_utc);
5845 str_empty = rb_fstring_lit("");
5846 rb_gc_register_mark_object(str_empty);
5847
5848 rb_cTime = rb_define_class("Time", rb_cObject);
5851
5852 rb_define_alloc_func(rb_cTime, time_s_alloc);
5853 rb_define_singleton_method(rb_cTime, "utc", time_s_mkutc, -1);
5854 rb_define_singleton_method(rb_cTime, "local", time_s_mktime, -1);
5855 rb_define_alias(scTime, "gm", "utc");
5856 rb_define_alias(scTime, "mktime", "local");
5857
5858 rb_define_method(rb_cTime, "to_i", time_to_i, 0);
5859 rb_define_method(rb_cTime, "to_f", time_to_f, 0);
5860 rb_define_method(rb_cTime, "to_r", time_to_r, 0);
5861 rb_define_method(rb_cTime, "<=>", time_cmp, 1);
5862 rb_define_method(rb_cTime, "eql?", time_eql, 1);
5863 rb_define_method(rb_cTime, "hash", time_hash, 0);
5864 rb_define_method(rb_cTime, "initialize_copy", time_init_copy, 1);
5865
5866 rb_define_method(rb_cTime, "localtime", time_localtime_m, -1);
5867 rb_define_method(rb_cTime, "gmtime", time_gmtime, 0);
5868 rb_define_method(rb_cTime, "utc", time_gmtime, 0);
5869 rb_define_method(rb_cTime, "getlocal", time_getlocaltime, -1);
5870 rb_define_method(rb_cTime, "getgm", time_getgmtime, 0);
5871 rb_define_method(rb_cTime, "getutc", time_getgmtime, 0);
5872
5873 rb_define_method(rb_cTime, "ctime", time_asctime, 0);
5874 rb_define_method(rb_cTime, "asctime", time_asctime, 0);
5875 rb_define_method(rb_cTime, "to_s", time_to_s, 0);
5876 rb_define_method(rb_cTime, "inspect", time_inspect, 0);
5877 rb_define_method(rb_cTime, "to_a", time_to_a, 0);
5878 rb_define_method(rb_cTime, "deconstruct_keys", time_deconstruct_keys, 1);
5879
5880 rb_define_method(rb_cTime, "+", time_plus, 1);
5881 rb_define_method(rb_cTime, "-", time_minus, 1);
5882
5883 rb_define_method(rb_cTime, "round", time_round, -1);
5884 rb_define_method(rb_cTime, "floor", time_floor, -1);
5885 rb_define_method(rb_cTime, "ceil", time_ceil, -1);
5886
5887 rb_define_method(rb_cTime, "sec", time_sec, 0);
5888 rb_define_method(rb_cTime, "min", time_min, 0);
5889 rb_define_method(rb_cTime, "hour", time_hour, 0);
5890 rb_define_method(rb_cTime, "mday", time_mday, 0);
5891 rb_define_method(rb_cTime, "day", time_mday, 0);
5892 rb_define_method(rb_cTime, "mon", time_mon, 0);
5893 rb_define_method(rb_cTime, "month", time_mon, 0);
5894 rb_define_method(rb_cTime, "year", time_year, 0);
5895 rb_define_method(rb_cTime, "wday", time_wday, 0);
5896 rb_define_method(rb_cTime, "yday", time_yday, 0);
5897 rb_define_method(rb_cTime, "isdst", time_isdst, 0);
5898 rb_define_method(rb_cTime, "dst?", time_isdst, 0);
5899 rb_define_method(rb_cTime, "zone", time_zone, 0);
5900 rb_define_method(rb_cTime, "gmtoff", rb_time_utc_offset, 0);
5901 rb_define_method(rb_cTime, "gmt_offset", rb_time_utc_offset, 0);
5902 rb_define_method(rb_cTime, "utc_offset", rb_time_utc_offset, 0);
5903
5904 rb_define_method(rb_cTime, "utc?", time_utc_p, 0);
5905 rb_define_method(rb_cTime, "gmt?", time_utc_p, 0);
5906
5907 rb_define_method(rb_cTime, "sunday?", time_sunday, 0);
5908 rb_define_method(rb_cTime, "monday?", time_monday, 0);
5909 rb_define_method(rb_cTime, "tuesday?", time_tuesday, 0);
5910 rb_define_method(rb_cTime, "wednesday?", time_wednesday, 0);
5911 rb_define_method(rb_cTime, "thursday?", time_thursday, 0);
5912 rb_define_method(rb_cTime, "friday?", time_friday, 0);
5913 rb_define_method(rb_cTime, "saturday?", time_saturday, 0);
5914
5915 rb_define_method(rb_cTime, "tv_sec", time_to_i, 0);
5916 rb_define_method(rb_cTime, "tv_usec", time_usec, 0);
5917 rb_define_method(rb_cTime, "usec", time_usec, 0);
5918 rb_define_method(rb_cTime, "tv_nsec", time_nsec, 0);
5919 rb_define_method(rb_cTime, "nsec", time_nsec, 0);
5920 rb_define_method(rb_cTime, "subsec", time_subsec, 0);
5921
5922 rb_define_method(rb_cTime, "strftime", time_strftime, 1);
5923
5924 /* methods for marshaling */
5925 rb_define_private_method(rb_cTime, "_dump", time_dump, -1);
5926 rb_define_private_method(scTime, "_load", time_load, 1);
5927#if 0
5928 /* Time will support marshal_dump and marshal_load in the future (1.9 maybe) */
5929 rb_define_private_method(rb_cTime, "marshal_dump", time_mdump, 0);
5930 rb_define_private_method(rb_cTime, "marshal_load", time_mload, 1);
5931#endif
5932
5933 if (debug_find_time_numguess) {
5934 rb_define_hooked_variable("$find_time_numguess", (VALUE *)&find_time_numguess,
5935 find_time_numguess_getter, NULL);
5936 }
5937
5938 rb_cTimeTM = Init_tm(rb_cTime, "tm");
5939}
5940
5941#include "timev.rbinc"
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1125
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:923
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:2236
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition class.c:955
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:2284
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Retrieves argument from argc and argv to given VALUE references according to the format string.
Definition class.c:2574
#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:3150
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:688
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:3274
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
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:3532
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
Definition object.c:3032
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:3101
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:3026
Encoding relates APIs.
static bool rb_enc_str_asciicompat_p(VALUE str)
Queries if the passed string is in an ASCII-compatible encoding.
Definition encoding.h:805
VALUE rb_enc_str_new(const char *ptr, long len, rb_encoding *enc)
Identical to rb_enc_str_new(), except it additionally takes an encoding.
Definition string.c:981
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1102
#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
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:280
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:2826
#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:3177
#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:3453
#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:2640
#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:3064
#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:2701
void rb_timespec_now(struct timespec *ts)
Fills the current time into the given struct.
Definition time.c:1931
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:2707
struct timespec rb_time_timespec(VALUE time)
Identical to rb_time_timeval(), except for return type.
Definition time.c:2870
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:2693
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:2853
struct timeval rb_time_interval(VALUE num)
Creates a "time interval".
Definition time.c:2847
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:2730
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:4984
struct timespec rb_time_timespec_interval(VALUE num)
Identical to rb_time_interval(), except for return type.
Definition time.c:2884
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:1606
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:2805
void rb_alias(VALUE klass, ID dst, ID src)
Resembles alias.
Definition vm_method.c:2140
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:664
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:276
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
Definition symbol.c:796
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.
VALUE rb_rescue(type *q, VALUE w, type *e, VALUE r)
An equivalent of rescue clause.
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c:1740
#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
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:528
static long RSTRING_LEN(VALUE str)
Queries the length of the string.
Definition rstring.h:484
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
Definition rstring.h:498
#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.
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:190
Definition timev.h:5
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:263
static bool rb_integer_type_p(VALUE obj)
Queries if the object is an instance of rb_cInteger.
Definition value_type.h:203
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:375