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