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