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