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