Ruby 4.1.0dev (2026-09-26 revision 227006291d35b2255b3f7a888d75102c129b0472)
time.c (227006291d35b2255b3f7a888d75102c129b0472)
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) {
1030 return rb_enc_interned_str(zone, len, rb_usascii_encoding());
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
1042 return rb_enc_interned_str(zone, len, rb_locale_encoding());
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 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/* Turn the special case 24:00:00 of already validated vtm into
2500 * 00:00:00 the next day */
2501static void
2502vtm_day_wraparound(struct vtm *vtm)
2503{
2504 if (vtm->hour < 24) return;
2505
2506 /* Assuming UTC and no care of DST, just reset hour and advance
2507 * date, not to discard the validated vtm. */
2508 vtm->hour = 0;
2509 vtm_add_day(vtm, 1);
2510}
2511
2512static VALUE time_init_vtm(VALUE time, struct vtm vtm, VALUE zone);
2513
2514/*
2515 * Sets the broken-out time information into _time_.
2516 * Returns _time_.
2517 */
2518static VALUE
2519time_init_args(rb_execution_context_t *ec, VALUE time, VALUE year, VALUE mon, VALUE mday,
2520 VALUE hour, VALUE min, VALUE sec, VALUE zone)
2521{
2522 struct vtm vtm;
2523
2524 vtm.wday = VTM_WDAY_INITVAL;
2525 vtm.yday = 0;
2526 vtm.zone = str_empty;
2527
2528 vtm.year = obj2vint(year);
2529
2530 vtm.mon = NIL_P(mon) ? 1 : month_arg(mon);
2531
2532 vtm.mday = NIL_P(mday) ? 1 : obj2ubits(mday, 5);
2533
2534 vtm.hour = NIL_P(hour) ? 0 : obj2ubits(hour, 5);
2535
2536 vtm.min = NIL_P(min) ? 0 : obj2ubits(min, 6);
2537
2538 if (NIL_P(sec)) {
2539 vtm.sec = 0;
2540 vtm.subsecx = INT2FIX(0);
2541 }
2542 else {
2543 VALUE subsecx;
2544 vtm.sec = obj2subsecx(sec, &subsecx);
2545 vtm.subsecx = subsecx;
2546 }
2547
2548 return time_init_vtm(time, vtm, zone);
2549}
2550
2551static VALUE
2552time_init_vtm(VALUE time, struct vtm vtm, VALUE zone)
2553{
2554 VALUE utc = Qnil;
2555 struct time_object *tobj;
2556
2557 vtm.isdst = VTM_ISDST_INITVAL;
2558 vtm.utc_offset = Qnil;
2559 const VALUE arg = zone;
2560 if (!NIL_P(arg)) {
2561 zone = Qnil;
2562 if (arg == ID2SYM(rb_intern("dst")))
2563 vtm.isdst = 1;
2564 else if (arg == ID2SYM(rb_intern("std")))
2565 vtm.isdst = 0;
2566 else if (maybe_tzobj_p(arg))
2567 zone = arg;
2568 else if (!NIL_P(utc = utc_offset_arg(arg)))
2569 vtm.utc_offset = utc == UTC_ZONE ? INT2FIX(0) : utc;
2570 else if (NIL_P(zone = find_timezone(time, arg)))
2571 invalid_utc_offset(arg);
2572 }
2573
2574 validate_vtm(&vtm);
2575
2576 time_modify(time);
2577 GetNewTimeval(time, tobj);
2578
2579 if (!NIL_P(zone)) {
2580 time_set_timew(time, tobj, timegmw(&vtm));
2581 vtm_day_wraparound(&vtm);
2582 time_set_vtm(time, tobj, vtm);
2583 tobj->vtm.tm_got = 1;
2584 TZMODE_SET_LOCALTIME(tobj);
2585 if (zone_timelocal(zone, time)) {
2586 return time;
2587 }
2588 else if (NIL_P(vtm.utc_offset = utc_offset_arg(zone))) {
2589 if (NIL_P(zone = find_timezone(time, zone)) || !zone_timelocal(zone, time))
2590 invalid_utc_offset(arg);
2591 }
2592 }
2593
2594 if (utc == UTC_ZONE) {
2595 time_set_timew(time, tobj, timegmw(&vtm));
2596 vtm.isdst = 0; /* No DST in UTC */
2597 vtm_day_wraparound(&vtm);
2598 time_set_vtm(time, tobj, vtm);
2599 tobj->vtm.tm_got = 1;
2600 TZMODE_SET_UTC(tobj);
2601 return time;
2602 }
2603
2604 TZMODE_SET_LOCALTIME(tobj);
2605 tobj->vtm.tm_got=0;
2606
2607 if (!NIL_P(vtm.utc_offset)) {
2608 VALUE off = vtm.utc_offset;
2609 vtm_add_offset(&vtm, off, -1);
2610 vtm.utc_offset = Qnil;
2611 time_set_timew(time, tobj, timegmw(&vtm));
2612
2613 return time_set_utc_offset(time, off);
2614 }
2615 else {
2616 time_set_timew(time, tobj, timelocalw(&vtm));
2617
2618 return time_localtime(time);
2619 }
2620}
2621
2622static int
2623two_digits(const char *ptr, const char *end, const char **endp, const char *name)
2624{
2625 ssize_t len = end - ptr;
2626 if (len < 2 || !have_2digits(ptr) || ((len > 2) && ISDIGIT(ptr[2]))) {
2627 VALUE mesg = rb_sprintf("two digits %s is expected", name);
2628 if (ptr[-1] == '-' || ptr[-1] == ':') {
2629 rb_str_catf(mesg, " after '%c'", ptr[-1]);
2630 }
2631 rb_str_catf(mesg, ": %.*s", ((len > 10) ? 10 : (int)(end - ptr)) + 1, ptr - 1);
2632 rb_exc_raise(rb_exc_new_str(rb_eArgError, mesg));
2633 }
2634 *endp = ptr + 2;
2635 return num_from_2digits(ptr);
2636}
2637
2638static VALUE
2639parse_int(const char *ptr, const char *end, const char **endp, size_t *ndigits, bool sign)
2640{
2641 ssize_t len = (end - ptr);
2642 int flags = sign ? RB_INT_PARSE_SIGN : 0;
2643 return rb_int_parse_cstr(ptr, len, (char **)endp, ndigits, 10, flags);
2644}
2645
2646/*
2647 * Parses _str_ and sets the broken-out time information into _time_.
2648 * If _str_ is not a String, returns +nil+, otherwise returns _time_.
2649 */
2650static VALUE
2651time_init_parse(rb_execution_context_t *ec, VALUE time, VALUE str, VALUE zone, VALUE precision)
2652{
2653 if (NIL_P(str = rb_check_string_type(str))) return Qnil;
2654 if (!rb_enc_str_asciicompat_p(str)) {
2655 rb_raise(rb_eArgError, "time string should have ASCII compatible encoding");
2656 }
2657
2658 size_t prec = NIL_P(precision) ? SIZE_MAX : NUM2SIZET(precision);
2659
2660 const char *const begin = RSTRING_PTR(str);
2661 const char *const end = RSTRING_END(str);
2662 const char *ptr = begin;
2663 VALUE year = Qnil, subsec = Qnil;
2664 int mon = -1, mday = -1, hour = -1, min = -1, sec = -1;
2665 size_t ndigits;
2666
2667 if ((ptr < end) && (ISSPACE(*ptr) || ISSPACE(*(end-1)))) {
2668 rb_raise(rb_eArgError, "can't parse: %+"PRIsVALUE, str);
2669 }
2670 year = parse_int(ptr, end, &ptr, &ndigits, true);
2671 if (NIL_P(year)) {
2672 rb_raise(rb_eArgError, "can't parse: %+"PRIsVALUE, str);
2673 }
2674 else if (ndigits < 4) {
2675 rb_raise(rb_eArgError, "year must be 4 or more digits: %.*s", (int)ndigits, ptr - ndigits);
2676 }
2677 else if (ptr == end) {
2678 goto only_year;
2679 }
2680 do {
2681#define peekable_p(n) ((ptrdiff_t)(n) < (end - ptr))
2682#define peek_n(c, n) (peekable_p(n) && ((unsigned char)ptr[n] == (c)))
2683#define peek(c) peek_n(c, 0)
2684#define peekc_n(n) (peekable_p(n) ? (int)(unsigned char)ptr[n] : -1)
2685#define peekc() peekc_n(0)
2686#define expect_two_digits(x, bits) \
2687 (((unsigned int)(x = two_digits(ptr + 1, end, &ptr, #x)) > (1U << bits) - 1) ? \
2688 rb_raise(rb_eArgError, #x" out of range") : (void)0)
2689 if (!peek('-')) break;
2690 expect_two_digits(mon, 4);
2691 if (!peek('-')) break;
2692 expect_two_digits(mday, 5);
2693 if (!peek(' ') && !peek('T')) break;
2694 const char *const time_part = ptr + 1;
2695 if (!ISDIGIT(peekc_n(1))) break;
2696#define nofraction(x) \
2697 if (peek('.')) { \
2698 rb_raise(rb_eArgError, "fraction " #x " is not supported: %.*s", \
2699 (int)(ptr + 1 - time_part), time_part); \
2700 }
2701#define need_colon(x) \
2702 if (!peek(':')) { \
2703 rb_raise(rb_eArgError, "missing " #x " part: %.*s", \
2704 (int)(ptr + 1 - time_part), time_part); \
2705 }
2706 expect_two_digits(hour, 5);
2707 nofraction(hour);
2708 need_colon(min);
2709 expect_two_digits(min, 6);
2710 nofraction(min);
2711 need_colon(sec);
2712 expect_two_digits(sec, 6);
2713 if (peek('.')) {
2714 ptr++;
2715 for (ndigits = 0; ndigits < prec && ISDIGIT(peekc_n(ndigits)); ++ndigits);
2716 if (!ndigits) {
2717 int clen = rb_enc_precise_mbclen(ptr, end, rb_enc_get(str));
2718 if (clen < 0) clen = 0;
2719 rb_raise(rb_eArgError, "subsecond expected after dot: %.*s",
2720 (int)(ptr - time_part) + clen, time_part);
2721 }
2722 subsec = parse_int(ptr, ptr + ndigits, &ptr, &ndigits, false);
2723 if (NIL_P(subsec)) break;
2724 while (ptr < end && ISDIGIT(*ptr)) ptr++;
2725 }
2726 } while (0);
2727 while (ptr < end && ISSPACE(*ptr)) ptr++;
2728 const char *const zstr = ptr;
2729 while (ptr < end && !ISSPACE(*ptr)) ptr++;
2730 const char *const zend = ptr;
2731 while (ptr < end && ISSPACE(*ptr)) ptr++;
2732 if (ptr < end) {
2733 VALUE mesg = rb_str_new_cstr("can't parse at: ");
2734 rb_str_cat(mesg, ptr, end - ptr);
2735 rb_exc_raise(rb_exc_new_str(rb_eArgError, mesg));
2736 }
2737 if (zend > zstr) {
2738 zone = rb_str_subseq(str, zstr - begin, zend - zstr);
2739 }
2740 else if (hour == -1) {
2741 rb_raise(rb_eArgError, "no time information");
2742 }
2743 if (!NIL_P(subsec)) {
2744 /* subseconds is the last using ndigits */
2745 if (ndigits < (size_t)TIME_SCALE_NUMDIGITS) {
2746 VALUE mul = rb_int_positive_pow(10, TIME_SCALE_NUMDIGITS - ndigits);
2747 subsec = rb_int_mul(subsec, mul);
2748 }
2749 else if (ndigits > (size_t)TIME_SCALE_NUMDIGITS) {
2750 VALUE num = rb_int_positive_pow(10, ndigits - TIME_SCALE_NUMDIGITS);
2751 subsec = rb_rational_new(subsec, num);
2752 }
2753 }
2754
2755only_year:
2756 ;
2757
2758 struct vtm vtm = {
2759 .wday = VTM_WDAY_INITVAL,
2760 .yday = 0,
2761 .zone = str_empty,
2762 .year = year,
2763 .mon = (mon < 0) ? 1 : mon,
2764 .mday = (mday < 0) ? 1 : mday,
2765 .hour = (hour < 0) ? 0 : hour,
2766 .min = (min < 0) ? 0 : min,
2767 .sec = (sec < 0) ? 0 : sec,
2768 .subsecx = NIL_P(subsec) ? INT2FIX(0) : subsec,
2769 };
2770 return time_init_vtm(time, vtm, zone);
2771}
2772
2773static void
2774subsec_normalize(wideint_t *secp, long *subsecp, const long maxsubsec)
2775{
2776 wideint_t sec = *secp;
2777 long subsec = *subsecp;
2778 long sec2;
2779
2780 if (UNLIKELY(subsec >= maxsubsec)) { /* subsec positive overflow */
2781 sec2 = subsec / maxsubsec;
2782 if (WIDEINT_MAX - sec2 < sec) {
2783 rb_raise(rb_eRangeError, "out of Time range");
2784 }
2785 subsec -= sec2 * maxsubsec;
2786 sec += sec2;
2787 }
2788 else if (UNLIKELY(subsec < 0)) { /* subsec negative overflow */
2789 sec2 = NDIV(subsec, maxsubsec); /* negative div */
2790 if (sec < WIDEINT_MIN - sec2) {
2791 rb_raise(rb_eRangeError, "out of Time range");
2792 }
2793 subsec -= sec2 * maxsubsec;
2794 sec += sec2;
2795 }
2796 *secp = sec;
2797 *subsecp = subsec;
2798}
2799
2800#define time_usec_normalize(secp, usecp) subsec_normalize(secp, usecp, 1000000)
2801#define time_nsec_normalize(secp, nsecp) subsec_normalize(secp, nsecp, 1000000000)
2802
2803static VALUE
2804time_new_timew(VALUE klass, wideval_t timew)
2805{
2806 VALUE time = time_s_alloc(klass);
2807 struct time_object *tobj;
2808
2809 tobj = RTYPEDDATA_GET_DATA(time); /* skip type check */
2810 TZMODE_SET_LOCALTIME(tobj);
2811 time_set_timew(time, tobj, timew);
2812
2813 return time;
2814}
2815
2816static wideint_t
2817TIMETtoWIDEINT(time_t t)
2818{
2819#if SIZEOF_TIME_T * CHAR_BIT - (SIGNEDNESS_OF_TIME_T < 0) > \
2820 SIZEOF_WIDEINT * CHAR_BIT - 1
2821 /* compare in bit size without sign bit */
2822 if (t > WIDEINT_MAX) rb_raise(rb_eArgError, "out of Time range");
2823#endif
2824 return (wideint_t)t;
2825}
2826
2827VALUE
2828rb_time_new(time_t sec, long usec)
2829{
2830 wideint_t isec = TIMETtoWIDEINT(sec);
2831 time_usec_normalize(&isec, &usec);
2832 return time_new_timew(rb_cTime, timenano2timew(isec, usec * 1000));
2833}
2834
2835/* returns localtime time object */
2836VALUE
2837rb_time_nano_new(time_t sec, long nsec)
2838{
2839 wideint_t isec = TIMETtoWIDEINT(sec);
2840 time_nsec_normalize(&isec, &nsec);
2841 return time_new_timew(rb_cTime, timenano2timew(isec, nsec));
2842}
2843
2844VALUE
2845rb_time_timespec_new(const struct timespec *ts, int offset)
2846{
2847 struct time_object *tobj;
2848 VALUE time = rb_time_nano_new(ts->tv_sec, ts->tv_nsec);
2849
2850 if (-86400 < offset && offset < 86400) { /* fixoff */
2851 GetTimeval(time, tobj);
2852 TZMODE_SET_FIXOFF(time, tobj, INT2FIX(offset));
2853 }
2854 else if (offset == INT_MAX) { /* localtime */
2855 }
2856 else if (offset == INT_MAX-1) { /* UTC */
2857 GetTimeval(time, tobj);
2858 TZMODE_SET_UTC(tobj);
2859 }
2860 else {
2861 rb_raise(rb_eArgError, "utc_offset out of range");
2862 }
2863
2864 return time;
2865}
2866
2867VALUE
2869{
2870 VALUE time = time_new_timew(rb_cTime, rb_time_magnify(v2w(timev)));
2871
2872 if (!NIL_P(off)) {
2873 VALUE zone = off;
2874
2875 if (maybe_tzobj_p(zone)) {
2876 time_gmtime(time);
2877 if (zone_timelocal(zone, time)) return time;
2878 }
2879 if (NIL_P(off = utc_offset_arg(off))) {
2880 off = zone;
2881 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
2882 time_gmtime(time);
2883 if (!zone_timelocal(zone, time)) invalid_utc_offset(off);
2884 return time;
2885 }
2886 else if (off == UTC_ZONE) {
2887 return time_gmtime(time);
2888 }
2889
2890 validate_utc_offset(off);
2891 time_set_utc_offset(time, off);
2892 return time;
2893 }
2894
2895 return time;
2896}
2897
2898static struct timespec
2899time_timespec(VALUE num, int interval)
2900{
2901 struct timespec t;
2902 const char *const tstr = interval ? "time interval" : "time";
2903 VALUE i, f, ary;
2904
2905#ifndef NEGATIVE_TIME_T
2906# define arg_range_check(v) \
2907 (((v) < 0) ? \
2908 rb_raise(rb_eArgError, "%s must not be negative", tstr) : \
2909 (void)0)
2910#else
2911# define arg_range_check(v) \
2912 ((interval && (v) < 0) ? \
2913 rb_raise(rb_eArgError, "time interval must not be negative") : \
2914 (void)0)
2915#endif
2916
2917 if (FIXNUM_P(num)) {
2918 t.tv_sec = NUM2TIMET(num);
2919 arg_range_check(t.tv_sec);
2920 t.tv_nsec = 0;
2921 }
2922 else if (RB_FLOAT_TYPE_P(num)) {
2923 double x = RFLOAT_VALUE(num);
2924 arg_range_check(x);
2925 {
2926 double f, d;
2927
2928 d = modf(x, &f);
2929 if (d >= 0) {
2930 t.tv_nsec = (int)(d*1e9+0.5);
2931 if (t.tv_nsec >= 1000000000) {
2932 t.tv_nsec -= 1000000000;
2933 f += 1;
2934 }
2935 }
2936 else if ((t.tv_nsec = (int)(-d*1e9+0.5)) > 0) {
2937 t.tv_nsec = 1000000000 - t.tv_nsec;
2938 f -= 1;
2939 }
2940 t.tv_sec = (time_t)f;
2941 if (f != t.tv_sec) {
2942 rb_raise(rb_eRangeError, "%f out of Time range", x);
2943 }
2944 }
2945 }
2946 else if (RB_BIGNUM_TYPE_P(num)) {
2947 t.tv_sec = NUM2TIMET(num);
2948 arg_range_check(t.tv_sec);
2949 t.tv_nsec = 0;
2950 }
2951 else {
2952 i = INT2FIX(1);
2953 ary = rb_check_funcall(num, id_divmod, 1, &i);
2954 if (!UNDEF_P(ary) && !NIL_P(ary = rb_check_array_type(ary))) {
2955 i = rb_ary_entry(ary, 0);
2956 f = rb_ary_entry(ary, 1);
2957 t.tv_sec = NUM2TIMET(i);
2958 arg_range_check(t.tv_sec);
2959 f = rb_funcall(f, '*', 1, INT2FIX(1000000000));
2960 t.tv_nsec = NUM2LONG(f);
2961 }
2962 else {
2963 rb_cant_convert(num, tstr);
2964 }
2965 }
2966 return t;
2967#undef arg_range_check
2968}
2969
2970static struct timeval
2971time_timeval(VALUE num, int interval)
2972{
2973 struct timespec ts;
2974 struct timeval tv;
2975
2976 ts = time_timespec(num, interval);
2977 tv.tv_sec = (TYPEOF_TIMEVAL_TV_SEC)ts.tv_sec;
2978 tv.tv_usec = (TYPEOF_TIMEVAL_TV_USEC)(ts.tv_nsec / 1000);
2979
2980 return tv;
2981}
2982
2983struct timeval
2985{
2986 return time_timeval(num, TRUE);
2987}
2988
2989struct timeval
2991{
2992 struct time_object *tobj;
2993 struct timeval t;
2994 struct timespec ts;
2995
2996 if (IsTimeval(time)) {
2997 GetTimeval(time, tobj);
2998 ts = timew2timespec(tobj->timew);
2999 t.tv_sec = (TYPEOF_TIMEVAL_TV_SEC)ts.tv_sec;
3000 t.tv_usec = (TYPEOF_TIMEVAL_TV_USEC)(ts.tv_nsec / 1000);
3001 return t;
3002 }
3003 return time_timeval(time, FALSE);
3004}
3005
3006struct timespec
3008{
3009 struct time_object *tobj;
3010 struct timespec t;
3011
3012 if (IsTimeval(time)) {
3013 GetTimeval(time, tobj);
3014 t = timew2timespec(tobj->timew);
3015 return t;
3016 }
3017 return time_timespec(time, FALSE);
3018}
3019
3020struct timespec
3022{
3023 return time_timespec(num, TRUE);
3024}
3025
3026static int
3027get_scale(VALUE unit)
3028{
3029 if (unit == ID2SYM(id_nanosecond) || unit == ID2SYM(id_nsec)) {
3030 return 1000000000;
3031 }
3032 else if (unit == ID2SYM(id_microsecond) || unit == ID2SYM(id_usec)) {
3033 return 1000000;
3034 }
3035 else if (unit == ID2SYM(id_millisecond)) {
3036 return 1000;
3037 }
3038 else {
3039 rb_raise(rb_eArgError, "unexpected unit: %"PRIsVALUE, unit);
3040 }
3041}
3042
3043static VALUE
3044time_s_at(rb_execution_context_t *ec, VALUE klass, VALUE time, VALUE subsec, VALUE unit, VALUE zone)
3045{
3046 VALUE t;
3047 wideval_t timew;
3048
3049 if (subsec) {
3050 int scale = get_scale(unit);
3051 time = num_exact(time);
3052 t = num_exact(subsec);
3053 timew = wadd(rb_time_magnify(v2w(time)), wmulquoll(v2w(t), TIME_SCALE, scale));
3054 t = time_new_timew(klass, timew);
3055 }
3056 else if (IsTimeval(time)) {
3057 struct time_object *tobj, *tobj2;
3058 GetTimeval(time, tobj);
3059 t = time_new_timew(klass, tobj->timew);
3060 GetTimeval(t, tobj2);
3061 TZMODE_COPY(tobj2, tobj);
3062 }
3063 else {
3064 timew = rb_time_magnify(v2w(num_exact(time)));
3065 t = time_new_timew(klass, timew);
3066 }
3067 if (!NIL_P(zone)) {
3068 time_zonelocal(t, zone);
3069 }
3070
3071 return t;
3072}
3073
3074static VALUE
3075time_s_at1(rb_execution_context_t *ec, VALUE klass, VALUE time)
3076{
3077 return time_s_at(ec, klass, time, Qfalse, ID2SYM(id_microsecond), Qnil);
3078}
3079
3080static const char months[][4] = {
3081 "jan", "feb", "mar", "apr", "may", "jun",
3082 "jul", "aug", "sep", "oct", "nov", "dec",
3083};
3084
3085static int
3086obj2int(VALUE obj)
3087{
3088 if (RB_TYPE_P(obj, T_STRING)) {
3089 obj = rb_str_to_inum(obj, 10, TRUE);
3090 }
3091
3092 return NUM2INT(obj);
3093}
3094
3095/* bits should be 0 <= x <= 31 */
3096static uint32_t
3097obj2ubits(VALUE obj, unsigned int bits)
3098{
3099 const unsigned int usable_mask = (1U << bits) - 1;
3100 unsigned int rv = (unsigned int)obj2int(obj);
3101
3102 if ((rv & usable_mask) != rv)
3103 rb_raise(rb_eArgError, "argument out of range");
3104 return (uint32_t)rv;
3105}
3106
3107static VALUE
3108obj2vint(VALUE obj)
3109{
3110 if (RB_TYPE_P(obj, T_STRING)) {
3111 obj = rb_str_to_inum(obj, 10, TRUE);
3112 }
3113 else {
3114 obj = rb_to_int(obj);
3115 }
3116
3117 return obj;
3118}
3119
3120static uint32_t
3121obj2subsecx(VALUE obj, VALUE *subsecx)
3122{
3123 VALUE subsec;
3124
3125 if (RB_TYPE_P(obj, T_STRING)) {
3126 obj = rb_str_to_inum(obj, 10, TRUE);
3127 *subsecx = INT2FIX(0);
3128 }
3129 else {
3130 divmodv(num_exact(obj), INT2FIX(1), &obj, &subsec);
3131 *subsecx = w2v(rb_time_magnify(v2w(subsec)));
3132 }
3133 return obj2ubits(obj, 6); /* vtm->sec */
3134}
3135
3136static VALUE
3137usec2subsecx(VALUE obj)
3138{
3139 if (RB_TYPE_P(obj, T_STRING)) {
3140 obj = rb_str_to_inum(obj, 10, TRUE);
3141 }
3142
3143 return mulquov(num_exact(obj), INT2FIX(TIME_SCALE), INT2FIX(1000000));
3144}
3145
3146static uint32_t
3147month_arg(VALUE arg)
3148{
3149 int i, mon;
3150
3151 if (FIXNUM_P(arg)) {
3152 return obj2ubits(arg, 4);
3153 }
3154
3155 mon = 0;
3156 VALUE s = rb_check_string_type(arg);
3157 if (!NIL_P(s) && RSTRING_LEN(s) > 0) {
3158 arg = s;
3159 for (i=0; i<12; i++) {
3160 if (RSTRING_LEN(s) == 3 &&
3161 STRNCASECMP(months[i], RSTRING_PTR(s), 3) == 0) {
3162 mon = i+1;
3163 break;
3164 }
3165 }
3166 }
3167 if (mon == 0) {
3168 mon = obj2ubits(arg, 4);
3169 }
3170 return mon;
3171}
3172
3173static VALUE
3174validate_utc_offset(VALUE utc_offset)
3175{
3176 if (le(utc_offset, INT2FIX(-86400)) || ge(utc_offset, INT2FIX(86400)))
3177 rb_raise(rb_eArgError, "utc_offset out of range");
3178 return utc_offset;
3179}
3180
3181static VALUE
3182validate_zone_name(VALUE zone_name)
3183{
3184 StringValueCStr(zone_name);
3185 return zone_name;
3186}
3187
3188static void
3189validate_vtm(struct vtm *vtm)
3190{
3191#define validate_vtm_range(mem, b, e) \
3192 ((vtm->mem < b || vtm->mem > e) ? \
3193 rb_raise(rb_eArgError, #mem" out of range") : (void)0)
3194 validate_vtm_range(mon, 1, 12);
3195 validate_vtm_range(mday, 1, 31);
3196 validate_vtm_range(hour, 0, 24);
3197 validate_vtm_range(min, 0, (vtm->hour == 24 ? 0 : 59));
3198 validate_vtm_range(sec, 0, (vtm->hour == 24 ? 0 : 60));
3199 if (lt(vtm->subsecx, INT2FIX(0)) || ge(vtm->subsecx, INT2FIX(TIME_SCALE)))
3200 rb_raise(rb_eArgError, "subsecx out of range");
3201 if (!NIL_P(vtm->utc_offset)) validate_utc_offset(vtm->utc_offset);
3202#undef validate_vtm_range
3203}
3204
3205static void
3206time_arg(int argc, const VALUE *argv, struct vtm *vtm)
3207{
3208 VALUE v[8];
3209 VALUE subsecx = INT2FIX(0);
3210
3211 vtm->year = INT2FIX(0);
3212 vtm->mon = 0;
3213 vtm->mday = 0;
3214 vtm->hour = 0;
3215 vtm->min = 0;
3216 vtm->sec = 0;
3217 vtm->subsecx = INT2FIX(0);
3218 vtm->utc_offset = Qnil;
3219 vtm->wday = 0;
3220 vtm->yday = 0;
3221 vtm->isdst = 0;
3222 vtm->zone = str_empty;
3223
3224 if (argc == 10) {
3225 v[0] = argv[5];
3226 v[1] = argv[4];
3227 v[2] = argv[3];
3228 v[3] = argv[2];
3229 v[4] = argv[1];
3230 v[5] = argv[0];
3231 v[6] = Qnil;
3232 vtm->isdst = RTEST(argv[8]) ? 1 : 0;
3233 }
3234 else {
3235 rb_scan_args(argc, argv, "17", &v[0],&v[1],&v[2],&v[3],&v[4],&v[5],&v[6],&v[7]);
3236 /* v[6] may be usec or zone (parsedate) */
3237 /* v[7] is wday (parsedate; ignored) */
3238 vtm->wday = VTM_WDAY_INITVAL;
3239 vtm->isdst = VTM_ISDST_INITVAL;
3240 }
3241
3242 vtm->year = obj2vint(v[0]);
3243
3244 if (NIL_P(v[1])) {
3245 vtm->mon = 1;
3246 }
3247 else {
3248 vtm->mon = month_arg(v[1]);
3249 }
3250
3251 if (NIL_P(v[2])) {
3252 vtm->mday = 1;
3253 }
3254 else {
3255 vtm->mday = obj2ubits(v[2], 5);
3256 }
3257
3258 /* normalize month-mday */
3259 switch (vtm->mon) {
3260 case 2:
3261 {
3262 /* this drops higher bits but it's not a problem to calc leap year */
3263 unsigned int mday2 = leap_year_v_p(vtm->year) ? 29 : 28;
3264 if (vtm->mday > mday2) {
3265 vtm->mday -= mday2;
3266 vtm->mon++;
3267 }
3268 }
3269 break;
3270 case 4:
3271 case 6:
3272 case 9:
3273 case 11:
3274 if (vtm->mday == 31) {
3275 vtm->mon++;
3276 vtm->mday = 1;
3277 }
3278 break;
3279 }
3280
3281 vtm->hour = NIL_P(v[3])?0:obj2ubits(v[3], 5);
3282
3283 vtm->min = NIL_P(v[4])?0:obj2ubits(v[4], 6);
3284
3285 if (!NIL_P(v[6]) && argc == 7) {
3286 vtm->sec = NIL_P(v[5])?0:obj2ubits(v[5],6);
3287 subsecx = usec2subsecx(v[6]);
3288 }
3289 else {
3290 /* when argc == 8, v[6] is timezone, but ignored */
3291 if (NIL_P(v[5])) {
3292 vtm->sec = 0;
3293 }
3294 else {
3295 vtm->sec = obj2subsecx(v[5], &subsecx);
3296 }
3297 }
3298 vtm->subsecx = subsecx;
3299
3300 validate_vtm(vtm);
3301 RB_GC_GUARD(subsecx);
3302}
3303
3304static int
3305leap_year_p(long y)
3306{
3307 /* TODO:
3308 * ensure about negative years in proleptic Gregorian calendar.
3309 */
3310 unsigned long uy = (unsigned long)(LIKELY(y >= 0) ? y : -y);
3311
3312 if (LIKELY(uy % 4 != 0)) return 0;
3313
3314 unsigned long century = uy / 100;
3315 if (LIKELY(uy != century * 100)) return 1;
3316 return century % 4 == 0;
3317}
3318
3319static time_t
3320timegm_noleapsecond(struct tm *tm)
3321{
3322 long tm_year = tm->tm_year;
3323 int tm_yday = calc_tm_yday(tm->tm_year, tm->tm_mon, tm->tm_mday);
3324
3325 /*
3326 * `Seconds Since the Epoch' in SUSv3:
3327 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
3328 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
3329 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
3330 */
3331 return tm->tm_sec + tm->tm_min*60 + tm->tm_hour*3600 +
3332 (time_t)(tm_yday +
3333 (tm_year-70)*365 +
3334 DIV(tm_year-69,4) -
3335 DIV(tm_year-1,100) +
3336 DIV(tm_year+299,400))*86400;
3337}
3338
3339#if 0
3340#define DEBUG_FIND_TIME_NUMGUESS
3341#define DEBUG_GUESSRANGE
3342#endif
3343
3344static const bool debug_guessrange =
3345#ifdef DEBUG_GUESSRANGE
3346 true;
3347#else
3348 false;
3349#endif
3350
3351#define DEBUG_REPORT_GUESSRANGE \
3352 (debug_guessrange ? debug_report_guessrange(guess_lo, guess_hi) : (void)0)
3353
3354static inline void
3355debug_report_guessrange(time_t guess_lo, time_t guess_hi)
3356{
3357 time_t guess_diff = guess_hi - guess_lo;
3358 fprintf(stderr, "find time guess range: %"PRI_TIMET_PREFIX"d - "
3359 "%"PRI_TIMET_PREFIX"d : %"PRI_TIMET_PREFIX"u\n",
3360 guess_lo, guess_hi, guess_diff);
3361}
3362
3363static const bool debug_find_time_numguess =
3364#ifdef DEBUG_FIND_TIME_NUMGUESS
3365 true;
3366#else
3367 false;
3368#endif
3369
3370#define DEBUG_FIND_TIME_NUMGUESS_INC \
3371 (void)(debug_find_time_numguess && find_time_numguess++),
3372static unsigned long long find_time_numguess;
3373
3374static VALUE
3375find_time_numguess_getter(ID name, VALUE *data)
3376{
3377 unsigned long long *numguess = (void *)data;
3378 return ULL2NUM(*numguess);
3379}
3380
3381static const char *
3382find_time_t(struct tm *tptr, int utc_p, time_t *tp)
3383{
3384 time_t guess, guess0, guess_lo, guess_hi;
3385 struct tm *tm, tm0, tm_lo, tm_hi;
3386 int d;
3387 int find_dst;
3388 struct tm result;
3389 int status;
3390 int tptr_tm_yday;
3391
3392#define GUESS(p) (DEBUG_FIND_TIME_NUMGUESS_INC (utc_p ? gmtime_with_leapsecond((p), &result) : LOCALTIME((p), result)))
3393
3394 guess_lo = TIMET_MIN;
3395 guess_hi = TIMET_MAX;
3396
3397 find_dst = 0 < tptr->tm_isdst;
3398
3399 /* /etc/localtime might be changed. reload it. */
3400 update_tz();
3401
3402 tm0 = *tptr;
3403 if (tm0.tm_mon < 0) {
3404 tm0.tm_mon = 0;
3405 tm0.tm_mday = 1;
3406 tm0.tm_hour = 0;
3407 tm0.tm_min = 0;
3408 tm0.tm_sec = 0;
3409 }
3410 else if (11 < tm0.tm_mon) {
3411 tm0.tm_mon = 11;
3412 tm0.tm_mday = 31;
3413 tm0.tm_hour = 23;
3414 tm0.tm_min = 59;
3415 tm0.tm_sec = 60;
3416 }
3417 else if (tm0.tm_mday < 1) {
3418 tm0.tm_mday = 1;
3419 tm0.tm_hour = 0;
3420 tm0.tm_min = 0;
3421 tm0.tm_sec = 0;
3422 }
3423 else if ((d = days_in_month_in(1900 + tm0.tm_year)[tm0.tm_mon]) < tm0.tm_mday) {
3424 tm0.tm_mday = d;
3425 tm0.tm_hour = 23;
3426 tm0.tm_min = 59;
3427 tm0.tm_sec = 60;
3428 }
3429 else if (tm0.tm_hour < 0) {
3430 tm0.tm_hour = 0;
3431 tm0.tm_min = 0;
3432 tm0.tm_sec = 0;
3433 }
3434 else if (23 < tm0.tm_hour) {
3435 tm0.tm_hour = 23;
3436 tm0.tm_min = 59;
3437 tm0.tm_sec = 60;
3438 }
3439 else if (tm0.tm_min < 0) {
3440 tm0.tm_min = 0;
3441 tm0.tm_sec = 0;
3442 }
3443 else if (59 < tm0.tm_min) {
3444 tm0.tm_min = 59;
3445 tm0.tm_sec = 60;
3446 }
3447 else if (tm0.tm_sec < 0) {
3448 tm0.tm_sec = 0;
3449 }
3450 else if (60 < tm0.tm_sec) {
3451 tm0.tm_sec = 60;
3452 }
3453
3454 DEBUG_REPORT_GUESSRANGE;
3455 guess0 = guess = timegm_noleapsecond(&tm0);
3456 tm = GUESS(&guess);
3457 if (tm) {
3458 d = tmcmp(tptr, tm);
3459 if (d == 0) { goto found; }
3460 if (d < 0) {
3461 guess_hi = guess;
3462 guess -= 24 * 60 * 60;
3463 }
3464 else {
3465 guess_lo = guess;
3466 guess += 24 * 60 * 60;
3467 }
3468 DEBUG_REPORT_GUESSRANGE;
3469 if (guess_lo < guess && guess < guess_hi && (tm = GUESS(&guess)) != NULL) {
3470 d = tmcmp(tptr, tm);
3471 if (d == 0) { goto found; }
3472 if (d < 0)
3473 guess_hi = guess;
3474 else
3475 guess_lo = guess;
3476 DEBUG_REPORT_GUESSRANGE;
3477 }
3478 }
3479
3480 tm = GUESS(&guess_lo);
3481 if (!tm) goto error;
3482 d = tmcmp(tptr, tm);
3483 if (d < 0) goto out_of_range;
3484 if (d == 0) { guess = guess_lo; goto found; }
3485 tm_lo = *tm;
3486
3487 tm = GUESS(&guess_hi);
3488 if (!tm) goto error;
3489 d = tmcmp(tptr, tm);
3490 if (d > 0) goto out_of_range;
3491 if (d == 0) { guess = guess_hi; goto found; }
3492 tm_hi = *tm;
3493
3494 DEBUG_REPORT_GUESSRANGE;
3495
3496 status = 1;
3497
3498 while (guess_lo + 1 < guess_hi) {
3499 binsearch:
3500 if (status == 0) {
3501 guess = guess_lo / 2 + guess_hi / 2;
3502 if (guess <= guess_lo)
3503 guess = guess_lo + 1;
3504 else if (guess >= guess_hi)
3505 guess = guess_hi - 1;
3506 status = 1;
3507 }
3508 else {
3509 if (status == 1) {
3510 time_t guess0_hi = timegm_noleapsecond(&tm_hi);
3511 guess = guess_hi - (guess0_hi - guess0);
3512 if (guess == guess_hi) /* hh:mm:60 tends to cause this condition. */
3513 guess--;
3514 status = 2;
3515 }
3516 else if (status == 2) {
3517 time_t guess0_lo = timegm_noleapsecond(&tm_lo);
3518 guess = guess_lo + (guess0 - guess0_lo);
3519 if (guess == guess_lo)
3520 guess++;
3521 status = 0;
3522 }
3523 if (guess <= guess_lo || guess_hi <= guess) {
3524 /* Previous guess is invalid. try binary search. */
3525 if (debug_guessrange) {
3526 if (guess <= guess_lo) {
3527 fprintf(stderr, "too small guess: %"PRI_TIMET_PREFIX"d"\
3528 " <= %"PRI_TIMET_PREFIX"d\n", guess, guess_lo);
3529 }
3530 if (guess_hi <= guess) {
3531 fprintf(stderr, "too big guess: %"PRI_TIMET_PREFIX"d"\
3532 " <= %"PRI_TIMET_PREFIX"d\n", guess_hi, guess);
3533 }
3534 }
3535 status = 0;
3536 goto binsearch;
3537 }
3538 }
3539
3540 tm = GUESS(&guess);
3541 if (!tm) goto error;
3542
3543 d = tmcmp(tptr, tm);
3544
3545 if (d < 0) {
3546 guess_hi = guess;
3547 tm_hi = *tm;
3548 DEBUG_REPORT_GUESSRANGE;
3549 }
3550 else if (d > 0) {
3551 guess_lo = guess;
3552 tm_lo = *tm;
3553 DEBUG_REPORT_GUESSRANGE;
3554 }
3555 else {
3556 goto found;
3557 }
3558 }
3559
3560 /* Given argument has no corresponding time_t. Let's extrapolate. */
3561 /*
3562 * `Seconds Since the Epoch' in SUSv3:
3563 * tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
3564 * (tm_year-70)*31536000 + ((tm_year-69)/4)*86400 -
3565 * ((tm_year-1)/100)*86400 + ((tm_year+299)/400)*86400
3566 */
3567
3568 tptr_tm_yday = calc_tm_yday(tptr->tm_year, tptr->tm_mon, tptr->tm_mday);
3569
3570 *tp = guess_lo +
3571 ((tptr->tm_year - tm_lo.tm_year) * 365 +
3572 DIV((tptr->tm_year-69), 4) -
3573 DIV((tptr->tm_year-1), 100) +
3574 DIV((tptr->tm_year+299), 400) -
3575 DIV((tm_lo.tm_year-69), 4) +
3576 DIV((tm_lo.tm_year-1), 100) -
3577 DIV((tm_lo.tm_year+299), 400) +
3578 tptr_tm_yday -
3579 tm_lo.tm_yday) * 86400 +
3580 (tptr->tm_hour - tm_lo.tm_hour) * 3600 +
3581 (tptr->tm_min - tm_lo.tm_min) * 60 +
3582 (tptr->tm_sec - (tm_lo.tm_sec == 60 ? 59 : tm_lo.tm_sec));
3583
3584 return NULL;
3585
3586 found:
3587 if (!utc_p) {
3588 /* If localtime is nonmonotonic, another result may exist. */
3589 time_t guess2;
3590 if (find_dst) {
3591 guess2 = guess - 2 * 60 * 60;
3592 tm = LOCALTIME(&guess2, result);
3593 if (tm) {
3594 if (tptr->tm_hour != (tm->tm_hour + 2) % 24 ||
3595 tptr->tm_min != tm->tm_min ||
3596 tptr->tm_sec != tm->tm_sec) {
3597 guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
3598 (tm->tm_min - tptr->tm_min) * 60 +
3599 (tm->tm_sec - tptr->tm_sec);
3600 if (tptr->tm_mday != tm->tm_mday)
3601 guess2 += 24 * 60 * 60;
3602 if (guess != guess2) {
3603 tm = LOCALTIME(&guess2, result);
3604 if (tm && tmcmp(tptr, tm) == 0) {
3605 if (guess < guess2)
3606 *tp = guess;
3607 else
3608 *tp = guess2;
3609 return NULL;
3610 }
3611 }
3612 }
3613 }
3614 }
3615 else {
3616 guess2 = guess + 2 * 60 * 60;
3617 tm = LOCALTIME(&guess2, result);
3618 if (tm) {
3619 if ((tptr->tm_hour + 2) % 24 != tm->tm_hour ||
3620 tptr->tm_min != tm->tm_min ||
3621 tptr->tm_sec != tm->tm_sec) {
3622 guess2 -= (tm->tm_hour - tptr->tm_hour) * 60 * 60 +
3623 (tm->tm_min - tptr->tm_min) * 60 +
3624 (tm->tm_sec - tptr->tm_sec);
3625 if (tptr->tm_mday != tm->tm_mday)
3626 guess2 -= 24 * 60 * 60;
3627 if (guess != guess2) {
3628 tm = LOCALTIME(&guess2, result);
3629 if (tm && tmcmp(tptr, tm) == 0) {
3630 if (guess < guess2)
3631 *tp = guess2;
3632 else
3633 *tp = guess;
3634 return NULL;
3635 }
3636 }
3637 }
3638 }
3639 }
3640 }
3641 *tp = guess;
3642 return NULL;
3643
3644 out_of_range:
3645 return "time out of range";
3646
3647 error:
3648 return "gmtime/localtime error";
3649}
3650
3651static int
3652vtmcmp(struct vtm *a, struct vtm *b)
3653{
3654 if (ne(a->year, b->year))
3655 return lt(a->year, b->year) ? -1 : 1;
3656 else if (a->mon != b->mon)
3657 return a->mon < b->mon ? -1 : 1;
3658 else if (a->mday != b->mday)
3659 return a->mday < b->mday ? -1 : 1;
3660 else if (a->hour != b->hour)
3661 return a->hour < b->hour ? -1 : 1;
3662 else if (a->min != b->min)
3663 return a->min < b->min ? -1 : 1;
3664 else if (a->sec != b->sec)
3665 return a->sec < b->sec ? -1 : 1;
3666 else if (ne(a->subsecx, b->subsecx))
3667 return lt(a->subsecx, b->subsecx) ? -1 : 1;
3668 else
3669 return 0;
3670}
3671
3672static int
3673tmcmp(struct tm *a, struct tm *b)
3674{
3675 if (a->tm_year != b->tm_year)
3676 return a->tm_year < b->tm_year ? -1 : 1;
3677 else if (a->tm_mon != b->tm_mon)
3678 return a->tm_mon < b->tm_mon ? -1 : 1;
3679 else if (a->tm_mday != b->tm_mday)
3680 return a->tm_mday < b->tm_mday ? -1 : 1;
3681 else if (a->tm_hour != b->tm_hour)
3682 return a->tm_hour < b->tm_hour ? -1 : 1;
3683 else if (a->tm_min != b->tm_min)
3684 return a->tm_min < b->tm_min ? -1 : 1;
3685 else if (a->tm_sec != b->tm_sec)
3686 return a->tm_sec < b->tm_sec ? -1 : 1;
3687 else
3688 return 0;
3689}
3690
3691/*
3692 * call-seq:
3693 * Time.utc(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0) -> new_time
3694 * Time.utc(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy) -> new_time
3695 *
3696 * Returns a new +Time+ object based the on given arguments,
3697 * in the UTC timezone.
3698 *
3699 * With one to seven arguments given,
3700 * the arguments are interpreted as in the first calling sequence above:
3701 *
3702 * Time.utc(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0)
3703 *
3704 * Examples:
3705 *
3706 * Time.utc(2000) # => 2000-01-01 00:00:00 UTC
3707 * Time.utc(-2000) # => -2000-01-01 00:00:00 UTC
3708 *
3709 * There are no minimum and maximum values for the required argument +year+.
3710 *
3711 * For the optional arguments:
3712 *
3713 * - +month+: Month in range (1..12), or case-insensitive
3714 * 3-letter month name:
3715 *
3716 * Time.utc(2000, 1) # => 2000-01-01 00:00:00 UTC
3717 * Time.utc(2000, 12) # => 2000-12-01 00:00:00 UTC
3718 * Time.utc(2000, 'jan') # => 2000-01-01 00:00:00 UTC
3719 * Time.utc(2000, 'JAN') # => 2000-01-01 00:00:00 UTC
3720 *
3721 * - +mday+: Month day in range(1..31):
3722 *
3723 * Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC
3724 * Time.utc(2000, 1, 31) # => 2000-01-31 00:00:00 UTC
3725 *
3726 * - +hour+: Hour in range (0..23), or 24 if +min+, +sec+, and +usec+
3727 * are zero:
3728 *
3729 * Time.utc(2000, 1, 1, 0) # => 2000-01-01 00:00:00 UTC
3730 * Time.utc(2000, 1, 1, 23) # => 2000-01-01 23:00:00 UTC
3731 * Time.utc(2000, 1, 1, 24) # => 2000-01-02 00:00:00 UTC
3732 *
3733 * - +min+: Minute in range (0..59):
3734 *
3735 * Time.utc(2000, 1, 1, 0, 0) # => 2000-01-01 00:00:00 UTC
3736 * Time.utc(2000, 1, 1, 0, 59) # => 2000-01-01 00:59:00 UTC
3737 *
3738 * - +sec+: Second in range (0..59), or 60 if +usec+ is zero:
3739 *
3740 * Time.utc(2000, 1, 1, 0, 0, 0) # => 2000-01-01 00:00:00 UTC
3741 * Time.utc(2000, 1, 1, 0, 0, 59) # => 2000-01-01 00:00:59 UTC
3742 * Time.utc(2000, 1, 1, 0, 0, 60) # => 2000-01-01 00:01:00 UTC
3743 *
3744 * - +usec+: Microsecond in range (0..999999):
3745 *
3746 * Time.utc(2000, 1, 1, 0, 0, 0, 0) # => 2000-01-01 00:00:00 UTC
3747 * Time.utc(2000, 1, 1, 0, 0, 0, 999999) # => 2000-01-01 00:00:00.999999 UTC
3748 *
3749 * The values may be:
3750 *
3751 * - Integers, as above.
3752 * - Numerics convertible to integers:
3753 *
3754 * Time.utc(Float(0.0), Rational(1, 1), 1.0, 0.0, 0.0, 0.0, 0.0)
3755 * # => 0000-01-01 00:00:00 UTC
3756 *
3757 * - String integers:
3758 *
3759 * a = %w[0 1 1 0 0 0 0 0]
3760 * # => ["0", "1", "1", "0", "0", "0", "0", "0"]
3761 * Time.utc(*a) # => 0000-01-01 00:00:00 UTC
3762 *
3763 * When exactly ten arguments are given,
3764 * the arguments are interpreted as in the second calling sequence above:
3765 *
3766 * Time.utc(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy)
3767 *
3768 * where the +dummy+ arguments are ignored:
3769 *
3770 * a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3771 * # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3772 * Time.utc(*a) # => 0005-04-03 02:01:00 UTC
3773 *
3774 * This form is useful for creating a +Time+ object from a 10-element
3775 * array returned by Time.to_a:
3776 *
3777 * t = Time.new(2000, 1, 2, 3, 4, 5, 6) # => 2000-01-02 03:04:05 +000006
3778 * a = t.to_a # => [5, 4, 3, 2, 1, 2000, 0, 2, false, nil]
3779 * Time.utc(*a) # => 2000-01-02 03:04:05 UTC
3780 *
3781 * The two forms have their first six arguments in common,
3782 * though in different orders;
3783 * the ranges of these common arguments are the same for both forms; see above.
3784 *
3785 * Raises an exception if the number of arguments is eight, nine,
3786 * or greater than ten.
3787 *
3788 * Related: Time.local.
3789 *
3790 */
3791static VALUE
3792time_s_mkutc(int argc, VALUE *argv, VALUE klass)
3793{
3794 struct vtm vtm;
3795
3796 time_arg(argc, argv, &vtm);
3797 return time_gmtime(time_new_timew(klass, timegmw(&vtm)));
3798}
3799
3800/*
3801 * call-seq:
3802 * Time.local(year, month = 1, mday = 1, hour = 0, min = 0, sec = 0, usec = 0) -> new_time
3803 * Time.local(sec, min, hour, mday, month, year, dummy, dummy, dummy, dummy) -> new_time
3804 *
3805 * Like Time.utc, except that the returned +Time+ object
3806 * has the local timezone, not the UTC timezone:
3807 *
3808 * # With seven arguments.
3809 * Time.local(0, 1, 2, 3, 4, 5, 6)
3810 * # => 0000-01-02 03:04:05.000006 -0600
3811 * # With exactly ten arguments.
3812 * Time.local(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
3813 * # => 0005-04-03 02:01:00 -0600
3814 *
3815 */
3816
3817static VALUE
3818time_s_mktime(int argc, VALUE *argv, VALUE klass)
3819{
3820 struct vtm vtm;
3821
3822 time_arg(argc, argv, &vtm);
3823 return time_localtime(time_new_timew(klass, timelocalw(&vtm)));
3824}
3825
3826/*
3827 * call-seq:
3828 * to_i -> integer
3829 *
3830 * Returns the value of +self+ as integer
3831 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3832 * subseconds are truncated (not rounded):
3833 *
3834 * Time.utc(1970, 1, 1, 0, 0, 0).to_i # => 0
3835 * Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_i # => 0
3836 * Time.utc(1950, 1, 1, 0, 0, 0).to_i # => -631152000
3837 * Time.utc(1990, 1, 1, 0, 0, 0).to_i # => 631152000
3838 *
3839 * Related: Time#to_f Time#to_r.
3840 */
3841
3842static VALUE
3843time_to_i(VALUE time)
3844{
3845 struct time_object *tobj;
3846
3847 GetTimeval(time, tobj);
3848 return w2v(wdiv(tobj->timew, WINT2FIXWV(TIME_SCALE)));
3849}
3850
3851/*
3852 * call-seq:
3853 * to_f -> float
3854 *
3855 * Returns the value of +self+ as a Float number
3856 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3857 * subseconds are included.
3858 *
3859 * The stored value of +self+ is a Rational,
3860 * which means that the returned value may be approximate:
3861 *
3862 * Time.utc(1970, 1, 1, 0, 0, 0).to_f # => 0.0
3863 * Time.utc(1970, 1, 1, 0, 0, 0, 999999).to_f # => 0.999999
3864 * Time.utc(1950, 1, 1, 0, 0, 0).to_f # => -631152000.0
3865 * Time.utc(1990, 1, 1, 0, 0, 0).to_f # => 631152000.0
3866 *
3867 * Related: Time#to_i, Time#to_r.
3868 */
3869
3870static VALUE
3871time_to_f(VALUE time)
3872{
3873 struct time_object *tobj;
3874
3875 GetTimeval(time, tobj);
3876 return rb_Float(rb_time_unmagnify_to_float(tobj->timew));
3877}
3878
3879/*
3880 * call-seq:
3881 * to_r -> rational
3882 *
3883 * Returns the value of +self+ as a Rational exact number of
3884 * {Epoch seconds}[rdoc-ref:Time@Epoch+Seconds];
3885 *
3886 * Time.now.to_r # => (16571402750320203/10000000)
3887 *
3888 * Related: Time#to_f, Time#to_i.
3889 */
3890
3891static VALUE
3892time_to_r(VALUE time)
3893{
3894 struct time_object *tobj;
3895 VALUE v;
3896
3897 GetTimeval(time, tobj);
3898 v = rb_time_unmagnify_to_rational(tobj->timew);
3899 if (!RB_TYPE_P(v, T_RATIONAL)) {
3900 v = rb_Rational1(v);
3901 }
3902 return v;
3903}
3904
3905/*
3906 * call-seq:
3907 * usec -> integer
3908 *
3909 * Returns the number of microseconds in the subseconds part of +self+
3910 * in the range (0..999_999);
3911 * lower-order digits are truncated, not rounded:
3912 *
3913 * t = Time.now # => 2022-07-11 14:59:47.5484697 -0500
3914 * t.usec # => 548469
3915 *
3916 * Related: Time#subsec (returns exact subseconds).
3917 */
3918
3919static VALUE
3920time_usec(VALUE time)
3921{
3922 struct time_object *tobj;
3923 wideval_t w, q, r;
3924
3925 GetTimeval(time, tobj);
3926
3927 w = wmod(tobj->timew, WINT2WV(TIME_SCALE));
3928 wmuldivmod(w, WINT2FIXWV(1000000), WINT2FIXWV(TIME_SCALE), &q, &r);
3929 return rb_to_int(w2v(q));
3930}
3931
3932/*
3933 * call-seq:
3934 * nsec -> integer
3935 *
3936 * Returns the number of nanoseconds in the subseconds part of +self+
3937 * in the range (0..999_999_999);
3938 * lower-order digits are truncated, not rounded:
3939 *
3940 * t = Time.now # => 2022-07-11 15:04:53.3219637 -0500
3941 * t.nsec # => 321963700
3942 *
3943 * Related: Time#subsec (returns exact subseconds).
3944 */
3945
3946static VALUE
3947time_nsec(VALUE time)
3948{
3949 struct time_object *tobj;
3950
3951 GetTimeval(time, tobj);
3952 return rb_to_int(w2v(wmulquoll(wmod(tobj->timew, WINT2WV(TIME_SCALE)), 1000000000, TIME_SCALE)));
3953}
3954
3955/*
3956 * call-seq:
3957 * subsec -> numeric
3958 *
3959 * Returns the exact subseconds for +self+ as a Numeric
3960 * (Integer or Rational):
3961 *
3962 * t = Time.now # => 2022-07-11 15:11:36.8490302 -0500
3963 * t.subsec # => (4245151/5000000)
3964 *
3965 * If the subseconds is zero, returns integer zero:
3966 *
3967 * t = Time.new(2000, 1, 1, 2, 3, 4) # => 2000-01-01 02:03:04 -0600
3968 * t.subsec # => 0
3969 *
3970 */
3971
3972static VALUE
3973time_subsec(VALUE time)
3974{
3975 struct time_object *tobj;
3976
3977 GetTimeval(time, tobj);
3978 return quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE));
3979}
3980
3981/*
3982 * call-seq:
3983 * self <=> other_time -> -1, 0, +1, or nil
3984 *
3985 * Compares +self+ with +other_time+; returns:
3986 *
3987 * - +-1+, if +self+ is less than +other_time+.
3988 * - +0+, if +self+ is equal to +other_time+.
3989 * - +1+, if +self+ is greater then +other_time+.
3990 * - +nil+, if +self+ and +other_time+ are incomparable.
3991 *
3992 * Examples:
3993 *
3994 * t = Time.now # => 2007-11-19 08:12:12 -0600
3995 * t2 = t + 2592000 # => 2007-12-19 08:12:12 -0600
3996 * t <=> t2 # => -1
3997 * t2 <=> t # => 1
3998 *
3999 * t = Time.now # => 2007-11-19 08:13:38 -0600
4000 * t2 = t + 0.1 # => 2007-11-19 08:13:38 -0600
4001 * t.nsec # => 98222999
4002 * t2.nsec # => 198222999
4003 * t <=> t2 # => -1
4004 * t2 <=> t # => 1
4005 * t <=> t # => 0
4006 *
4007 */
4008
4009static VALUE
4010time_cmp(VALUE time1, VALUE time2)
4011{
4012 struct time_object *tobj1, *tobj2;
4013 int n;
4014
4015 GetTimeval(time1, tobj1);
4016 if (IsTimeval(time2)) {
4017 GetTimeval(time2, tobj2);
4018 n = wcmp(tobj1->timew, tobj2->timew);
4019 }
4020 else {
4021 return rb_invcmp(time1, time2);
4022 }
4023 if (n == 0) return INT2FIX(0);
4024 if (n > 0) return INT2FIX(1);
4025 return INT2FIX(-1);
4026}
4027
4028/*
4029 * call-seq:
4030 * eql?(other_time)
4031 *
4032 * Returns +true+ if +self+ and +other_time+ are
4033 * both +Time+ objects with the exact same time value.
4034 */
4035
4036static VALUE
4037time_eql(VALUE time1, VALUE time2)
4038{
4039 struct time_object *tobj1, *tobj2;
4040
4041 GetTimeval(time1, tobj1);
4042 if (IsTimeval(time2)) {
4043 GetTimeval(time2, tobj2);
4044 return rb_equal(w2v(tobj1->timew), w2v(tobj2->timew));
4045 }
4046 return Qfalse;
4047}
4048
4049/*
4050 * call-seq:
4051 * utc? -> true or false
4052 *
4053 * Returns +true+ if +self+ represents a time in UTC (GMT):
4054 *
4055 * now = Time.now
4056 * # => 2022-08-18 10:24:13.5398485 -0500
4057 * now.utc? # => false
4058 * now.getutc.utc? # => true
4059 * utc = Time.utc(2000, 1, 1, 20, 15, 1)
4060 * # => 2000-01-01 20:15:01 UTC
4061 * utc.utc? # => true
4062 *
4063 * +Time+ objects created with these methods are considered to be in
4064 * UTC:
4065 *
4066 * * Time.utc
4067 * * Time#utc
4068 * * Time#getutc
4069 *
4070 * Objects created in other ways will not be treated as UTC even if
4071 * the environment variable "TZ" is "UTC".
4072 *
4073 * Related: Time.utc.
4074 */
4075
4076static VALUE
4077time_utc_p(VALUE time)
4078{
4079 struct time_object *tobj;
4080
4081 GetTimeval(time, tobj);
4082 return RBOOL(TZMODE_UTC_P(tobj));
4083}
4084
4085/*
4086 * call-seq:
4087 * hash -> integer
4088 *
4089 * Returns the integer hash code for +self+.
4090 *
4091 * Related: Object#hash.
4092 */
4093
4094static VALUE
4095time_hash(VALUE time)
4096{
4097 struct time_object *tobj;
4098
4099 GetTimeval(time, tobj);
4100 return rb_hash(w2v(tobj->timew));
4101}
4102
4103/* :nodoc: */
4104static VALUE
4105time_init_copy(VALUE copy, VALUE time)
4106{
4107 struct time_object *tobj, *tcopy;
4108
4109 if (!OBJ_INIT_COPY(copy, time)) return copy;
4110 GetTimeval(time, tobj);
4111 GetNewTimeval(copy, tcopy);
4112
4113 time_set_timew(copy, tcopy, tobj->timew);
4114 time_set_vtm(copy, tcopy, tobj->vtm);
4115
4116 return copy;
4117}
4118
4119static VALUE
4120time_dup(VALUE time)
4121{
4122 VALUE dup = time_s_alloc(rb_obj_class(time));
4123 time_init_copy(dup, time);
4124 return dup;
4125}
4126
4127static VALUE
4128time_localtime(VALUE time)
4129{
4130 struct time_object *tobj;
4131 struct vtm vtm;
4132 VALUE zone;
4133
4134 GetTimeval(time, tobj);
4135 if (TZMODE_LOCALTIME_P(tobj)) {
4136 if (tobj->vtm.tm_got)
4137 return time;
4138 }
4139 else {
4140 time_modify(time);
4141 }
4142
4143 zone = tobj->vtm.zone;
4144 if (maybe_tzobj_p(zone) && zone_localtime(zone, time)) {
4145 return time;
4146 }
4147
4148 if (!localtimew(tobj->timew, &vtm))
4149 rb_raise(rb_eArgError, "localtime error");
4150 time_set_vtm(time, tobj, vtm);
4151
4152 tobj->vtm.tm_got = 1;
4153 TZMODE_SET_LOCALTIME(tobj);
4154 return time;
4155}
4156
4157static VALUE
4158time_zonelocal(VALUE time, VALUE off)
4159{
4160 VALUE zone = off;
4161 if (maybe_tzobj_p(zone) && zone_localtime(zone, time)) return time;
4162
4163 if (NIL_P(off = utc_offset_arg(off))) {
4164 off = zone;
4165 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
4166 if (!zone_localtime(zone, time)) invalid_utc_offset(off);
4167 return time;
4168 }
4169 else if (off == UTC_ZONE) {
4170 return time_gmtime(time);
4171 }
4172 validate_utc_offset(off);
4173
4174 time_set_utc_offset(time, off);
4175 return time_fixoff(time);
4176}
4177
4178/*
4179 * call-seq:
4180 * localtime -> self
4181 * localtime(zone) -> self
4182 *
4183 * With no argument given:
4184 *
4185 * - Returns +self+ if +self+ is already a local time.
4186 * - Otherwise returns +self+, converted to the user's local timezone:
4187 *
4188 * t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC
4189 * t.localtime # => 2000-01-01 14:15:01 -0600
4190 *
4191 * With argument +zone+ given,
4192 * returns +self+, converted to the given time zone:
4193 *
4194 * t = Time.utc(2000, 1, 1, 20, 15, 1) # => 2000-01-01 20:15:01 UTC
4195 * t.localtime("-09:00") # => 2000-01-01 11:15:01 -0900
4196 *
4197 * For forms of argument +zone+, see
4198 * {Timezone Specifiers}[rdoc-ref:Time@Timezone+Specifiers].
4199 *
4200 */
4201
4202static VALUE
4203time_localtime_m(int argc, VALUE *argv, VALUE time)
4204{
4205 VALUE off;
4206
4207 if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
4208 return time_zonelocal(time, off);
4209 }
4210
4211 return time_localtime(time);
4212}
4213
4214/*
4215 * call-seq:
4216 * utc -> self
4217 *
4218 * Returns +self+, converted to the UTC timezone:
4219 *
4220 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4221 * t.utc? # => false
4222 * t.utc # => 2000-01-01 06:00:00 UTC
4223 * t.utc? # => true
4224 *
4225 * Related: Time#getutc (returns a new converted +Time+ object).
4226 */
4227
4228static VALUE
4229time_gmtime(VALUE time)
4230{
4231 struct time_object *tobj;
4232 struct vtm vtm;
4233
4234 GetTimeval(time, tobj);
4235 if (TZMODE_UTC_P(tobj)) {
4236 if (tobj->vtm.tm_got)
4237 return time;
4238 }
4239 else {
4240 time_modify(time);
4241 }
4242
4243 vtm.zone = str_utc;
4244 GMTIMEW(tobj->timew, &vtm);
4245 time_set_vtm(time, tobj, vtm);
4246
4247 tobj->vtm.tm_got = 1;
4248 TZMODE_SET_UTC(tobj);
4249 return time;
4250}
4251
4252static VALUE
4253time_fixoff(VALUE time)
4254{
4255 struct time_object *tobj;
4256 struct vtm vtm;
4257 VALUE off, zone;
4258
4259 GetTimeval(time, tobj);
4260 if (TZMODE_FIXOFF_P(tobj)) {
4261 if (tobj->vtm.tm_got)
4262 return time;
4263 }
4264 else {
4265 time_modify(time);
4266 }
4267
4268 if (TZMODE_FIXOFF_P(tobj))
4269 off = tobj->vtm.utc_offset;
4270 else
4271 off = INT2FIX(0);
4272
4273 GMTIMEW(tobj->timew, &vtm);
4274
4275 zone = tobj->vtm.zone;
4276 vtm_add_offset(&vtm, off, +1);
4277
4278 time_set_vtm(time, tobj, vtm);
4279 RB_OBJ_WRITE_UNALIGNED(time, &tobj->vtm.zone, zone);
4280
4281 tobj->vtm.tm_got = 1;
4282 TZMODE_SET_FIXOFF(time, tobj, off);
4283 return time;
4284}
4285
4286/*
4287 * call-seq:
4288 * getlocal(zone = nil) -> new_time
4289 *
4290 * Returns a new +Time+ object representing the value of +self+
4291 * converted to a given timezone;
4292 * if +zone+ is +nil+, the local timezone is used:
4293 *
4294 * t = Time.utc(2000) # => 2000-01-01 00:00:00 UTC
4295 * t.getlocal # => 1999-12-31 18:00:00 -0600
4296 * t.getlocal('+12:00') # => 2000-01-01 12:00:00 +1200
4297 *
4298 * For forms of argument +zone+, see
4299 * {Timezone Specifiers}[rdoc-ref:Time@Timezone+Specifiers].
4300 *
4301 */
4302
4303static VALUE
4304time_getlocaltime(int argc, VALUE *argv, VALUE time)
4305{
4306 VALUE off;
4307
4308 if (rb_check_arity(argc, 0, 1) && !NIL_P(off = argv[0])) {
4309 VALUE zone = off;
4310 if (maybe_tzobj_p(zone)) {
4311 VALUE t = time_dup(time);
4312 if (zone_localtime(off, t)) return t;
4313 }
4314
4315 if (NIL_P(off = utc_offset_arg(off))) {
4316 off = zone;
4317 if (NIL_P(zone = find_timezone(time, off))) invalid_utc_offset(off);
4318 time = time_dup(time);
4319 if (!zone_localtime(zone, time)) invalid_utc_offset(off);
4320 return time;
4321 }
4322 else if (off == UTC_ZONE) {
4323 return time_gmtime(time_dup(time));
4324 }
4325 validate_utc_offset(off);
4326
4327 time = time_dup(time);
4328 time_set_utc_offset(time, off);
4329 return time_fixoff(time);
4330 }
4331
4332 return time_localtime(time_dup(time));
4333}
4334
4335/*
4336 * call-seq:
4337 * getutc -> new_time
4338 *
4339 * Returns a new +Time+ object representing the value of +self+
4340 * converted to the UTC timezone:
4341 *
4342 * local = Time.local(2000) # => 2000-01-01 00:00:00 -0600
4343 * local.utc? # => false
4344 * utc = local.getutc # => 2000-01-01 06:00:00 UTC
4345 * utc.utc? # => true
4346 * utc == local # => true
4347 *
4348 */
4349
4350static VALUE
4351time_getgmtime(VALUE time)
4352{
4353 return time_gmtime(time_dup(time));
4354}
4355
4356static VALUE
4357time_get_tm(VALUE time, struct time_object *tobj)
4358{
4359 if (TZMODE_UTC_P(tobj)) return time_gmtime(time);
4360 if (TZMODE_FIXOFF_P(tobj)) return time_fixoff(time);
4361 return time_localtime(time);
4362}
4363
4364static VALUE strftime_cstr(const char *fmt, size_t len, VALUE time, rb_encoding *enc);
4365#define strftimev(fmt, time, enc) strftime_cstr((fmt), rb_strlen_lit(fmt), (time), (enc))
4366
4367/*
4368 * call-seq:
4369 * ctime -> string
4370 *
4371 * Returns a string representation of +self+,
4372 * formatted by <tt>strftime('%a %b %e %T %Y')</tt>
4373 * or its shorthand version <tt>strftime('%c')</tt>;
4374 * see {Formats for Dates and Times}[rdoc-ref:strftime_formatting.rdoc]:
4375 *
4376 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4377 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4378 * t.strftime('%a %b %e %T %Y') # => "Sun Dec 31 23:59:59 2000"
4379 * t.strftime('%c') # => "Sun Dec 31 23:59:59 2000"
4380 *
4381 * Related: Time#to_s, Time#inspect:
4382 *
4383 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4384 * t.to_s # => "2000-12-31 23:59:59 +0000"
4385 *
4386 */
4387
4388static VALUE
4389time_asctime(VALUE time)
4390{
4391 return strftimev("%a %b %e %T %Y", time, rb_usascii_encoding());
4392}
4393
4394/*
4395 * call-seq:
4396 * to_s -> string
4397 *
4398 * Returns a string representation of +self+, without subseconds:
4399 *
4400 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4401 * t.to_s # => "2000-12-31 23:59:59 +0000"
4402 *
4403 * Related: Time#ctime, Time#inspect:
4404 *
4405 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4406 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4407 *
4408 */
4409
4410static VALUE
4411time_to_s(VALUE time)
4412{
4413 struct time_object *tobj;
4414
4415 GetTimeval(time, tobj);
4416 if (TZMODE_UTC_P(tobj))
4417 return strftimev("%Y-%m-%d %H:%M:%S UTC", time, rb_usascii_encoding());
4418 else
4419 return strftimev("%Y-%m-%d %H:%M:%S %z", time, rb_usascii_encoding());
4420}
4421
4422/*
4423 * call-seq:
4424 * inspect -> string
4425 *
4426 * Returns a string representation of +self+ with subseconds:
4427 *
4428 * t = Time.new(2000, 12, 31, 23, 59, 59, 0.5)
4429 * t.inspect # => "2000-12-31 23:59:59.5 +000001"
4430 *
4431 * Related: Time#ctime, Time#to_s:
4432 *
4433 * t.ctime # => "Sun Dec 31 23:59:59 2000"
4434 * t.to_s # => "2000-12-31 23:59:59 +0000"
4435 *
4436 */
4437
4438static VALUE
4439time_inspect(VALUE time)
4440{
4441 struct time_object *tobj;
4442 VALUE str, subsec;
4443
4444 GetTimeval(time, tobj);
4445 str = strftimev("%Y-%m-%d %H:%M:%S", time, rb_usascii_encoding());
4446 subsec = w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE)));
4447 if (subsec == INT2FIX(0)) {
4448 }
4449 else if (FIXNUM_P(subsec) && FIX2LONG(subsec) < TIME_SCALE) {
4450 long len;
4451 rb_str_catf(str, ".%09ld", FIX2LONG(subsec));
4452 for (len=RSTRING_LEN(str); RSTRING_PTR(str)[len-1] == '0' && len > 0; len--)
4453 ;
4454 rb_str_resize(str, len);
4455 }
4456 else {
4457 rb_str_cat_cstr(str, " ");
4458 subsec = quov(subsec, INT2FIX(TIME_SCALE));
4459 rb_str_concat(str, rb_obj_as_string(subsec));
4460 }
4461 if (TZMODE_UTC_P(tobj)) {
4462 rb_str_cat_cstr(str, " UTC");
4463 }
4464 else {
4465 /* ?TODO: subsecond offset */
4466 long off = NUM2LONG(rb_funcall(tobj->vtm.utc_offset, rb_intern("round"), 0));
4467 char sign = (off < 0) ? (off = -off, '-') : '+';
4468 int sec = off % 60;
4469 int min = (off /= 60) % 60;
4470 off /= 60;
4471 rb_str_catf(str, " %c%.2d%.2d", sign, (int)off, min);
4472 if (sec) rb_str_catf(str, "%.2d", sec);
4473 }
4474 return str;
4475}
4476
4477static VALUE
4478time_add0(VALUE klass, const struct time_object *tobj, VALUE torig, VALUE offset, int sign)
4479{
4480 VALUE result;
4481 struct time_object *result_tobj;
4482
4483 offset = num_exact(offset);
4484 if (sign < 0)
4485 result = time_new_timew(klass, wsub(tobj->timew, rb_time_magnify(v2w(offset))));
4486 else
4487 result = time_new_timew(klass, wadd(tobj->timew, rb_time_magnify(v2w(offset))));
4488 GetTimeval(result, result_tobj);
4489 TZMODE_COPY(result_tobj, tobj);
4490
4491 return result;
4492}
4493
4494static VALUE
4495time_add(const struct time_object *tobj, VALUE torig, VALUE offset, int sign)
4496{
4497 return time_add0(rb_cTime, tobj, torig, offset, sign);
4498}
4499
4500/*
4501 * call-seq:
4502 * self + numeric -> new_time
4503 *
4504 * Returns a new +Time+ object whose value is the sum of the numeric value
4505 * of +self+ and the given +numeric+:
4506 *
4507 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4508 * t + (60 * 60 * 24) # => 2000-01-02 00:00:00 -0600
4509 * t + 0.5 # => 2000-01-01 00:00:00.5 -0600
4510 *
4511 * Related: Time#-.
4512 */
4513
4514static VALUE
4515time_plus(VALUE time1, VALUE time2)
4516{
4517 struct time_object *tobj;
4518 GetTimeval(time1, tobj);
4519
4520 if (IsTimeval(time2)) {
4521 rb_raise(rb_eTypeError, "time + time?");
4522 }
4523 return time_add(tobj, time1, time2, 1);
4524}
4525
4526/*
4527 * call-seq:
4528 * self - numeric -> new_time
4529 * self - other_time -> float
4530 *
4531 * When +numeric+ is given,
4532 * returns a new +Time+ object whose value is the difference
4533 * of the numeric value of +self+ and +numeric+:
4534 *
4535 * t = Time.new(2000) # => 2000-01-01 00:00:00 -0600
4536 * t - (60 * 60 * 24) # => 1999-12-31 00:00:00 -0600
4537 * t - 0.5 # => 1999-12-31 23:59:59.5 -0600
4538 *
4539 * When +other_time+ is given,
4540 * returns a Float whose value is the difference
4541 * of the numeric values of +self+ and +other_time+ in seconds:
4542 *
4543 * t - t # => 0.0
4544 *
4545 * Related: Time#+.
4546 */
4547
4548static VALUE
4549time_minus(VALUE time1, VALUE time2)
4550{
4551 struct time_object *tobj;
4552
4553 GetTimeval(time1, tobj);
4554 if (IsTimeval(time2)) {
4555 struct time_object *tobj2;
4556
4557 GetTimeval(time2, tobj2);
4558 return rb_Float(rb_time_unmagnify_to_float(wsub(tobj->timew, tobj2->timew)));
4559 }
4560 return time_add(tobj, time1, time2, -1);
4561}
4562
4563static VALUE
4564ndigits_denominator(VALUE ndigits)
4565{
4566 long nd = NUM2LONG(ndigits);
4567
4568 if (nd < 0) {
4569 rb_raise(rb_eArgError, "negative ndigits given");
4570 }
4571 if (nd == 0) {
4572 return INT2FIX(1);
4573 }
4574 return rb_rational_new(INT2FIX(1),
4575 rb_int_positive_pow(10, (unsigned long)nd));
4576}
4577
4578/*
4579 * call-seq:
4580 * round(ndigits = 0) -> new_time
4581 *
4582 * Returns a new +Time+ object whose numeric value is that of +self+,
4583 * with its seconds value rounded to precision +ndigits+:
4584 *
4585 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4586 * t # => 2010-03-30 05:43:25.123456789 UTC
4587 * t.round # => 2010-03-30 05:43:25 UTC
4588 * t.round(0) # => 2010-03-30 05:43:25 UTC
4589 * t.round(1) # => 2010-03-30 05:43:25.1 UTC
4590 * t.round(2) # => 2010-03-30 05:43:25.12 UTC
4591 * t.round(3) # => 2010-03-30 05:43:25.123 UTC
4592 * t.round(4) # => 2010-03-30 05:43:25.1235 UTC
4593 *
4594 * t = Time.utc(1999, 12,31, 23, 59, 59)
4595 * t # => 1999-12-31 23:59:59 UTC
4596 * (t + 0.4).round # => 1999-12-31 23:59:59 UTC
4597 * (t + 0.49).round # => 1999-12-31 23:59:59 UTC
4598 * (t + 0.5).round # => 2000-01-01 00:00:00 UTC
4599 * (t + 1.4).round # => 2000-01-01 00:00:00 UTC
4600 * (t + 1.49).round # => 2000-01-01 00:00:00 UTC
4601 * (t + 1.5).round # => 2000-01-01 00:00:01 UTC
4602 *
4603 * Related: Time#ceil, Time#floor.
4604 */
4605
4606static VALUE
4607time_round(int argc, VALUE *argv, VALUE time)
4608{
4609 VALUE ndigits, v, den;
4610 struct time_object *tobj;
4611
4612 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4613 den = INT2FIX(1);
4614 else
4615 den = ndigits_denominator(ndigits);
4616
4617 GetTimeval(time, tobj);
4618 v = w2v(rb_time_unmagnify(tobj->timew));
4619
4620 v = modv(v, den);
4621 if (lt(v, quov(den, INT2FIX(2))))
4622 return time_add(tobj, time, v, -1);
4623 else
4624 return time_add(tobj, time, subv(den, v), 1);
4625}
4626
4627/*
4628 * call-seq:
4629 * floor(ndigits = 0) -> new_time
4630 *
4631 * Returns a new +Time+ object whose numerical value
4632 * is less than or equal to +self+ with its seconds
4633 * truncated to precision +ndigits+:
4634 *
4635 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4636 * t # => 2010-03-30 05:43:25.123456789 UTC
4637 * t.floor # => 2010-03-30 05:43:25 UTC
4638 * t.floor(2) # => 2010-03-30 05:43:25.12 UTC
4639 * t.floor(4) # => 2010-03-30 05:43:25.1234 UTC
4640 * t.floor(6) # => 2010-03-30 05:43:25.123456 UTC
4641 * t.floor(8) # => 2010-03-30 05:43:25.12345678 UTC
4642 * t.floor(10) # => 2010-03-30 05:43:25.123456789 UTC
4643 *
4644 * t = Time.utc(1999, 12, 31, 23, 59, 59)
4645 * t # => 1999-12-31 23:59:59 UTC
4646 * (t + 0.4).floor # => 1999-12-31 23:59:59 UTC
4647 * (t + 0.9).floor # => 1999-12-31 23:59:59 UTC
4648 * (t + 1.4).floor # => 2000-01-01 00:00:00 UTC
4649 * (t + 1.9).floor # => 2000-01-01 00:00:00 UTC
4650 *
4651 * Related: Time#ceil, Time#round.
4652 */
4653
4654static VALUE
4655time_floor(int argc, VALUE *argv, VALUE time)
4656{
4657 VALUE ndigits, v, den;
4658 struct time_object *tobj;
4659
4660 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4661 den = INT2FIX(1);
4662 else
4663 den = ndigits_denominator(ndigits);
4664
4665 GetTimeval(time, tobj);
4666 v = w2v(rb_time_unmagnify(tobj->timew));
4667
4668 v = modv(v, den);
4669 return time_add(tobj, time, v, -1);
4670}
4671
4672/*
4673 * call-seq:
4674 * ceil(ndigits = 0) -> new_time
4675 *
4676 * Returns a new +Time+ object whose numerical value
4677 * is greater than or equal to +self+ with its seconds
4678 * truncated to precision +ndigits+:
4679 *
4680 * t = Time.utc(2010, 3, 30, 5, 43, 25.123456789r)
4681 * t # => 2010-03-30 05:43:25.123456789 UTC
4682 * t.ceil # => 2010-03-30 05:43:26 UTC
4683 * t.ceil(2) # => 2010-03-30 05:43:25.13 UTC
4684 * t.ceil(4) # => 2010-03-30 05:43:25.1235 UTC
4685 * t.ceil(6) # => 2010-03-30 05:43:25.123457 UTC
4686 * t.ceil(8) # => 2010-03-30 05:43:25.12345679 UTC
4687 * t.ceil(10) # => 2010-03-30 05:43:25.123456789 UTC
4688 *
4689 * t = Time.utc(1999, 12, 31, 23, 59, 59)
4690 * t # => 1999-12-31 23:59:59 UTC
4691 * (t + 0.4).ceil # => 2000-01-01 00:00:00 UTC
4692 * (t + 0.9).ceil # => 2000-01-01 00:00:00 UTC
4693 * (t + 1.4).ceil # => 2000-01-01 00:00:01 UTC
4694 * (t + 1.9).ceil # => 2000-01-01 00:00:01 UTC
4695 *
4696 * Related: Time#floor, Time#round.
4697 */
4698
4699static VALUE
4700time_ceil(int argc, VALUE *argv, VALUE time)
4701{
4702 VALUE ndigits, v, den;
4703 struct time_object *tobj;
4704
4705 if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0]))
4706 den = INT2FIX(1);
4707 else
4708 den = ndigits_denominator(ndigits);
4709
4710 GetTimeval(time, tobj);
4711 v = w2v(rb_time_unmagnify(tobj->timew));
4712
4713 v = modv(v, den);
4714 if (!rb_equal(v, INT2FIX(0))) {
4715 v = subv(den, v);
4716 }
4717 return time_add(tobj, time, v, 1);
4718}
4719
4720/*
4721 * call-seq:
4722 * sec -> integer
4723 *
4724 * Returns the integer second of the minute for +self+,
4725 * in range (0..60):
4726 *
4727 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4728 * # => 2000-01-02 03:04:05 +000006
4729 * t.sec # => 5
4730 *
4731 * Note: the second value may be 60 when there is a
4732 * {leap second}[https://en.wikipedia.org/wiki/Leap_second].
4733 *
4734 * Related: Time#year, Time#mon, Time#min.
4735 */
4736
4737static VALUE
4738time_sec(VALUE time)
4739{
4740 struct time_object *tobj;
4741
4742 GetTimeval(time, tobj);
4743 MAKE_TM(time, tobj);
4744 return INT2FIX(tobj->vtm.sec);
4745}
4746
4747/*
4748 * call-seq:
4749 * min -> integer
4750 *
4751 * Returns the integer minute of the hour for +self+,
4752 * in range (0..59):
4753 *
4754 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4755 * # => 2000-01-02 03:04:05 +000006
4756 * t.min # => 4
4757 *
4758 * Related: Time#year, Time#mon, Time#sec.
4759 */
4760
4761static VALUE
4762time_min(VALUE time)
4763{
4764 struct time_object *tobj;
4765
4766 GetTimeval(time, tobj);
4767 MAKE_TM(time, tobj);
4768 return INT2FIX(tobj->vtm.min);
4769}
4770
4771/*
4772 * call-seq:
4773 * hour -> integer
4774 *
4775 * Returns the integer hour of the day for +self+,
4776 * in range (0..23):
4777 *
4778 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4779 * # => 2000-01-02 03:04:05 +000006
4780 * t.hour # => 3
4781 *
4782 * Related: Time#year, Time#mon, Time#min.
4783 */
4784
4785static VALUE
4786time_hour(VALUE time)
4787{
4788 struct time_object *tobj;
4789
4790 GetTimeval(time, tobj);
4791 MAKE_TM(time, tobj);
4792 return INT2FIX(tobj->vtm.hour);
4793}
4794
4795/*
4796 * call-seq:
4797 * mday -> integer
4798 *
4799 * Returns the integer day of the month for +self+,
4800 * in range (1..31):
4801 *
4802 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4803 * # => 2000-01-02 03:04:05 +000006
4804 * t.mday # => 2
4805 *
4806 * Related: Time#year, Time#hour, Time#min.
4807 */
4808
4809static VALUE
4810time_mday(VALUE time)
4811{
4812 struct time_object *tobj;
4813
4814 GetTimeval(time, tobj);
4815 MAKE_TM(time, tobj);
4816 return INT2FIX(tobj->vtm.mday);
4817}
4818
4819/*
4820 * call-seq:
4821 * mon -> integer
4822 *
4823 * Returns the integer month of the year for +self+,
4824 * in range (1..12):
4825 *
4826 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4827 * # => 2000-01-02 03:04:05 +000006
4828 * t.mon # => 1
4829 *
4830 * Related: Time#year, Time#hour, Time#min.
4831 */
4832
4833static VALUE
4834time_mon(VALUE time)
4835{
4836 struct time_object *tobj;
4837
4838 GetTimeval(time, tobj);
4839 MAKE_TM(time, tobj);
4840 return INT2FIX(tobj->vtm.mon);
4841}
4842
4843/*
4844 * call-seq:
4845 * year -> integer
4846 *
4847 * Returns the integer year for +self+:
4848 *
4849 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4850 * # => 2000-01-02 03:04:05 +000006
4851 * t.year # => 2000
4852 *
4853 * Related: Time#mon, Time#hour, Time#min.
4854 */
4855
4856static VALUE
4857time_year(VALUE time)
4858{
4859 struct time_object *tobj;
4860
4861 GetTimeval(time, tobj);
4862 MAKE_TM(time, tobj);
4863 return tobj->vtm.year;
4864}
4865
4866/*
4867 * call-seq:
4868 * wday -> integer
4869 *
4870 * Returns the integer day of the week for +self+,
4871 * in range (0..6), with Sunday as zero.
4872 *
4873 * t = Time.new(2000, 1, 2, 3, 4, 5, 6)
4874 * # => 2000-01-02 03:04:05 +000006
4875 * t.wday # => 0
4876 * t.sunday? # => true
4877 *
4878 * Related: Time#year, Time#hour, Time#min.
4879 */
4880
4881static VALUE
4882time_wday(VALUE time)
4883{
4884 struct time_object *tobj;
4885
4886 GetTimeval(time, tobj);
4887 MAKE_TM_ENSURE(time, tobj, tobj->vtm.wday != VTM_WDAY_INITVAL);
4888 return INT2FIX((int)tobj->vtm.wday);
4889}
4890
4891#define wday_p(n) {\
4892 return RBOOL(time_wday(time) == INT2FIX(n)); \
4893}
4894
4895/*
4896 * call-seq:
4897 * sunday? -> true or false
4898 *
4899 * Returns +true+ if +self+ represents a Sunday, +false+ otherwise:
4900 *
4901 * t = Time.utc(2000, 1, 2) # => 2000-01-02 00:00:00 UTC
4902 * t.sunday? # => true
4903 *
4904 * Related: Time#monday?, Time#tuesday?, Time#wednesday?.
4905 */
4906
4907static VALUE
4908time_sunday(VALUE time)
4909{
4910 wday_p(0);
4911}
4912
4913/*
4914 * call-seq:
4915 * monday? -> true or false
4916 *
4917 * Returns +true+ if +self+ represents a Monday, +false+ otherwise:
4918 *
4919 * t = Time.utc(2000, 1, 3) # => 2000-01-03 00:00:00 UTC
4920 * t.monday? # => true
4921 *
4922 * Related: Time#tuesday?, Time#wednesday?, Time#thursday?.
4923 */
4924
4925static VALUE
4926time_monday(VALUE time)
4927{
4928 wday_p(1);
4929}
4930
4931/*
4932 * call-seq:
4933 * tuesday? -> true or false
4934 *
4935 * Returns +true+ if +self+ represents a Tuesday, +false+ otherwise:
4936 *
4937 * t = Time.utc(2000, 1, 4) # => 2000-01-04 00:00:00 UTC
4938 * t.tuesday? # => true
4939 *
4940 * Related: Time#wednesday?, Time#thursday?, Time#friday?.
4941 */
4942
4943static VALUE
4944time_tuesday(VALUE time)
4945{
4946 wday_p(2);
4947}
4948
4949/*
4950 * call-seq:
4951 * wednesday? -> true or false
4952 *
4953 * Returns +true+ if +self+ represents a Wednesday, +false+ otherwise:
4954 *
4955 * t = Time.utc(2000, 1, 5) # => 2000-01-05 00:00:00 UTC
4956 * t.wednesday? # => true
4957 *
4958 * Related: Time#thursday?, Time#friday?, Time#saturday?.
4959 */
4960
4961static VALUE
4962time_wednesday(VALUE time)
4963{
4964 wday_p(3);
4965}
4966
4967/*
4968 * call-seq:
4969 * thursday? -> true or false
4970 *
4971 * Returns +true+ if +self+ represents a Thursday, +false+ otherwise:
4972 *
4973 * t = Time.utc(2000, 1, 6) # => 2000-01-06 00:00:00 UTC
4974 * t.thursday? # => true
4975 *
4976 * Related: Time#friday?, Time#saturday?, Time#sunday?.
4977 */
4978
4979static VALUE
4980time_thursday(VALUE time)
4981{
4982 wday_p(4);
4983}
4984
4985/*
4986 * call-seq:
4987 * friday? -> true or false
4988 *
4989 * Returns +true+ if +self+ represents a Friday, +false+ otherwise:
4990 *
4991 * t = Time.utc(2000, 1, 7) # => 2000-01-07 00:00:00 UTC
4992 * t.friday? # => true
4993 *
4994 * Related: Time#saturday?, Time#sunday?, Time#monday?.
4995 */
4996
4997static VALUE
4998time_friday(VALUE time)
4999{
5000 wday_p(5);
5001}
5002
5003/*
5004 * call-seq:
5005 * saturday? -> true or false
5006 *
5007 * Returns +true+ if +self+ represents a Saturday, +false+ otherwise:
5008 *
5009 * t = Time.utc(2000, 1, 1) # => 2000-01-01 00:00:00 UTC
5010 * t.saturday? # => true
5011 *
5012 * Related: Time#sunday?, Time#monday?, Time#tuesday?.
5013 */
5014
5015static VALUE
5016time_saturday(VALUE time)
5017{
5018 wday_p(6);
5019}
5020
5021/*
5022 * call-seq:
5023 * yday -> integer
5024 *
5025 * Returns the integer day of the year of +self+, in range (1..366).
5026 *
5027 * Time.new(2000, 1, 1).yday # => 1
5028 * Time.new(2000, 12, 31).yday # => 366
5029 */
5030
5031static VALUE
5032time_yday(VALUE time)
5033{
5034 struct time_object *tobj;
5035
5036 GetTimeval(time, tobj);
5037 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5038 return INT2FIX(tobj->vtm.yday);
5039}
5040
5041/*
5042 * call-seq:
5043 * dst? -> true or false
5044 *
5045 * Returns +true+ if +self+ is in daylight saving time, +false+ otherwise:
5046 *
5047 * t = Time.local(2000, 1, 1) # => 2000-01-01 00:00:00 -0600
5048 * t.zone # => "Central Standard Time"
5049 * t.dst? # => false
5050 * t = Time.local(2000, 7, 1) # => 2000-07-01 00:00:00 -0500
5051 * t.zone # => "Central Daylight Time"
5052 * t.dst? # => true
5053 *
5054 */
5055
5056static VALUE
5057time_isdst(VALUE time)
5058{
5059 struct time_object *tobj;
5060
5061 GetTimeval(time, tobj);
5062 MAKE_TM(time, tobj);
5063 if (tobj->vtm.isdst == VTM_ISDST_INITVAL) {
5064 rb_raise(rb_eRuntimeError, "isdst is not set yet");
5065 }
5066 return RBOOL(tobj->vtm.isdst);
5067}
5068
5069/*
5070 * call-seq:
5071 * time.zone -> string or timezone
5072 *
5073 * Returns the string name of the time zone for +self+:
5074 *
5075 * Time.utc(2000, 1, 1).zone # => "UTC"
5076 * Time.new(2000, 1, 1).zone # => "Central Standard Time"
5077 */
5078
5079static VALUE
5080time_zone(VALUE time)
5081{
5082 struct time_object *tobj;
5083 VALUE zone;
5084
5085 GetTimeval(time, tobj);
5086 MAKE_TM(time, tobj);
5087
5088 if (TZMODE_UTC_P(tobj)) {
5089 return rb_usascii_str_new_cstr("UTC");
5090 }
5091 zone = tobj->vtm.zone;
5092 if (NIL_P(zone))
5093 return Qnil;
5094
5095 if (RB_TYPE_P(zone, T_STRING))
5096 zone = rb_str_dup(zone);
5097 return zone;
5098}
5099
5100/*
5101 * call-seq:
5102 * utc_offset -> integer
5103 *
5104 * Returns the offset in seconds between the timezones of UTC and +self+:
5105 *
5106 * Time.utc(2000, 1, 1).utc_offset # => 0
5107 * Time.local(2000, 1, 1).utc_offset # => -21600 # -6*3600, or minus six hours.
5108 *
5109 */
5110
5111VALUE
5113{
5114 struct time_object *tobj;
5115
5116 GetTimeval(time, tobj);
5117
5118 if (TZMODE_UTC_P(tobj)) {
5119 return INT2FIX(0);
5120 }
5121 else {
5122 MAKE_TM(time, tobj);
5123 return tobj->vtm.utc_offset;
5124 }
5125}
5126
5127/*
5128 * call-seq:
5129 * to_a -> array
5130 *
5131 * Returns a 10-element array of values representing +self+:
5132 *
5133 * Time.utc(2000, 1, 1).to_a
5134 * # => [0, 0, 0, 1, 1, 2000, 6, 1, false, "UTC"]
5135 * # [sec, min, hour, day, mon, year, wday, yday, dst?, zone]
5136 *
5137 * The returned array is suitable for use as an argument to Time.utc or Time.local
5138 * to create a new +Time+ object.
5139 *
5140 */
5141
5142static VALUE
5143time_to_a(VALUE time)
5144{
5145 struct time_object *tobj;
5146
5147 GetTimeval(time, tobj);
5148 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5149 return rb_ary_new3(10,
5150 INT2FIX(tobj->vtm.sec),
5151 INT2FIX(tobj->vtm.min),
5152 INT2FIX(tobj->vtm.hour),
5153 INT2FIX(tobj->vtm.mday),
5154 INT2FIX(tobj->vtm.mon),
5155 tobj->vtm.year,
5156 INT2FIX(tobj->vtm.wday),
5157 INT2FIX(tobj->vtm.yday),
5158 RBOOL(tobj->vtm.isdst),
5159 time_zone(time));
5160}
5161
5162/*
5163 * call-seq:
5164 * deconstruct_keys(array_of_names_or_nil) -> hash
5165 *
5166 * Returns a hash of the name/value pairs, to use in pattern matching.
5167 * Possible keys are: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>,
5168 * <tt>:yday</tt>, <tt>:wday</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>,
5169 * <tt>:subsec</tt>, <tt>:dst</tt>, <tt>:zone</tt>.
5170 *
5171 * Possible usages:
5172 *
5173 * t = Time.utc(2022, 10, 5, 21, 25, 30)
5174 *
5175 * if t in wday: 3, day: ..7 # uses deconstruct_keys underneath
5176 * puts "first Wednesday of the month"
5177 * end
5178 * #=> prints "first Wednesday of the month"
5179 *
5180 * case t
5181 * in year: ...2022
5182 * puts "too old"
5183 * in month: ..9
5184 * puts "quarter 1-3"
5185 * in wday: 1..5, month:
5186 * puts "working day in month #{month}"
5187 * end
5188 * #=> prints "working day in month 10"
5189 *
5190 * Note that deconstruction by pattern can also be combined with class check:
5191 *
5192 * if t in Time(wday: 3, day: ..7)
5193 * puts "first Wednesday of the month"
5194 * end
5195 *
5196 */
5197static VALUE
5198time_deconstruct_keys(VALUE time, VALUE keys)
5199{
5200 struct time_object *tobj;
5201 VALUE h;
5202 long i;
5203
5204 GetTimeval(time, tobj);
5205 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5206
5207 if (NIL_P(keys)) {
5208 h = rb_hash_new_capa(11);
5209
5210 rb_hash_aset(h, sym_year, tobj->vtm.year);
5211 rb_hash_aset(h, sym_month, INT2FIX(tobj->vtm.mon));
5212 rb_hash_aset(h, sym_day, INT2FIX(tobj->vtm.mday));
5213 rb_hash_aset(h, sym_yday, INT2FIX(tobj->vtm.yday));
5214 rb_hash_aset(h, sym_wday, INT2FIX(tobj->vtm.wday));
5215 rb_hash_aset(h, sym_hour, INT2FIX(tobj->vtm.hour));
5216 rb_hash_aset(h, sym_min, INT2FIX(tobj->vtm.min));
5217 rb_hash_aset(h, sym_sec, INT2FIX(tobj->vtm.sec));
5218 rb_hash_aset(h, sym_subsec,
5219 quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
5220 rb_hash_aset(h, sym_dst, RBOOL(tobj->vtm.isdst));
5221 rb_hash_aset(h, sym_zone, time_zone(time));
5222
5223 return h;
5224 }
5225 if (UNLIKELY(!RB_TYPE_P(keys, T_ARRAY))) {
5226 rb_raise(rb_eTypeError,
5227 "wrong argument type %"PRIsVALUE" (expected Array or nil)",
5228 rb_obj_class(keys));
5229
5230 }
5231
5232 h = rb_hash_new_capa(RARRAY_LEN(keys));
5233
5234 for (i=0; i<RARRAY_LEN(keys); i++) {
5235 VALUE key = RARRAY_AREF(keys, i);
5236
5237 if (sym_year == key) rb_hash_aset(h, key, tobj->vtm.year);
5238 if (sym_month == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mon));
5239 if (sym_day == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.mday));
5240 if (sym_yday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.yday));
5241 if (sym_wday == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.wday));
5242 if (sym_hour == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.hour));
5243 if (sym_min == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.min));
5244 if (sym_sec == key) rb_hash_aset(h, key, INT2FIX(tobj->vtm.sec));
5245 if (sym_subsec == key) {
5246 rb_hash_aset(h, key, quov(w2v(wmod(tobj->timew, WINT2FIXWV(TIME_SCALE))), INT2FIX(TIME_SCALE)));
5247 }
5248 if (sym_dst == key) rb_hash_aset(h, key, RBOOL(tobj->vtm.isdst));
5249 if (sym_zone == key) rb_hash_aset(h, key, time_zone(time));
5250 }
5251 return h;
5252}
5253
5254static VALUE
5255rb_strftime_alloc(const char *format, size_t format_len, rb_encoding *enc,
5256 VALUE time, struct vtm *vtm, wideval_t timew, int gmt)
5257{
5258 VALUE timev = Qnil;
5259 struct timespec ts;
5260
5261 if (!timew2timespec_exact(timew, &ts))
5262 timev = w2v(rb_time_unmagnify(timew));
5263
5264 if (NIL_P(timev)) {
5265 return rb_strftime_timespec(format, format_len, enc, time, vtm, &ts, gmt);
5266 }
5267 else {
5268 return rb_strftime(format, format_len, enc, time, vtm, timev, gmt);
5269 }
5270}
5271
5272static VALUE
5273strftime_cstr(const char *fmt, size_t len, VALUE time, rb_encoding *enc)
5274{
5275 struct time_object *tobj;
5276 VALUE str;
5277
5278 GetTimeval(time, tobj);
5279 MAKE_TM(time, tobj);
5280 str = rb_strftime_alloc(fmt, len, enc, time, &tobj->vtm, tobj->timew, TZMODE_UTC_P(tobj));
5281 if (!str) rb_raise(rb_eArgError, "invalid format: %s", fmt);
5282 return str;
5283}
5284
5285/*
5286 * call-seq:
5287 * strftime(format_string) -> string
5288 *
5289 * Returns a string representation of +self+,
5290 * formatted according to the given string +format+.
5291 * See {Formats for Dates and Times}[rdoc-ref:strftime_formatting.rdoc].
5292 */
5293
5294static VALUE
5295time_strftime(VALUE time, VALUE format)
5296{
5297 struct time_object *tobj;
5298 const char *fmt;
5299 long len;
5300 rb_encoding *enc;
5301 VALUE tmp;
5302
5303 GetTimeval(time, tobj);
5304 MAKE_TM_ENSURE(time, tobj, tobj->vtm.yday != 0);
5305 StringValue(format);
5306 if (!rb_enc_str_asciicompat_p(format)) {
5307 rb_raise(rb_eArgError, "format should have ASCII compatible encoding");
5308 }
5309 tmp = rb_str_tmp_frozen_acquire(format);
5310 fmt = RSTRING_PTR(tmp);
5311 len = RSTRING_LEN(tmp);
5312 enc = rb_enc_get(format);
5313 if (len == 0) {
5314 rb_warning("strftime called with empty format string");
5315 return rb_enc_str_new(0, 0, enc);
5316 }
5317 else {
5318 VALUE str = rb_strftime_alloc(fmt, len, enc, time, &tobj->vtm, tobj->timew,
5319 TZMODE_UTC_P(tobj));
5320 rb_str_tmp_frozen_release(format, tmp);
5321 if (!str) rb_raise(rb_eArgError, "invalid format: %"PRIsVALUE, format);
5322 return str;
5323 }
5324}
5325
5326/*
5327 * call-seq:
5328 * xmlschema(fraction_digits=0) -> string
5329 *
5330 * Returns a string which represents the time as a dateTime defined by XML
5331 * Schema:
5332 *
5333 * CCYY-MM-DDThh:mm:ssTZD
5334 * CCYY-MM-DDThh:mm:ss.sssTZD
5335 *
5336 * where TZD is Z or [+-]hh:mm.
5337 *
5338 * If self is a UTC time, Z is used as TZD. [+-]hh:mm is used otherwise.
5339 *
5340 * +fraction_digits+ specifies a number of digits to use for fractional
5341 * seconds. Its default value is 0.
5342 *
5343 * t = Time.now
5344 * t.xmlschema # => "2011-10-05T22:26:12-04:00"
5345 */
5346
5347static VALUE
5348time_xmlschema(int argc, VALUE *argv, VALUE time)
5349{
5350 long fraction_digits = 0;
5351 rb_check_arity(argc, 0, 1);
5352 if (argc > 0) {
5353 fraction_digits = NUM2LONG(argv[0]);
5354 if (fraction_digits < 0) {
5355 fraction_digits = 0;
5356 }
5357 }
5358
5359 struct time_object *tobj;
5360
5361 GetTimeval(time, tobj);
5362 MAKE_TM(time, tobj);
5363
5364 const long size_after_year = sizeof("-MM-DDTHH:MM:SS+ZH:ZM") + fraction_digits
5365 + (fraction_digits > 0);
5366 VALUE str;
5367 char *ptr;
5368
5369# define fill_digits_long(len, prec, n) \
5370 for (int fill_it = 1, written = snprintf(ptr, len, "%0*ld", prec, n); \
5371 fill_it; ptr += written, fill_it = 0)
5372
5373 if (FIXNUM_P(tobj->vtm.year)) {
5374 long year = FIX2LONG(tobj->vtm.year);
5375 int year_width = (year < 0) + rb_strlen_lit("YYYY");
5376 int w = (year >= -9999 && year <= 9999 ? year_width : (year < 0) + (int)DECIMAL_SIZE_OF(year));
5377 str = rb_usascii_str_new(0, w + size_after_year);
5378 ptr = RSTRING_PTR(str);
5379 fill_digits_long(w + 1, year_width, year) {
5380 if (year >= -9999 && year <= 9999) {
5381 RUBY_ASSERT(written == year_width);
5382 }
5383 else {
5384 RUBY_ASSERT(written >= year_width);
5385 RUBY_ASSERT(written <= w);
5386 }
5387 }
5388 }
5389 else {
5390 str = rb_int2str(tobj->vtm.year, 10);
5391 rb_str_modify_expand(str, size_after_year);
5392 ptr = RSTRING_END(str);
5393 }
5394
5395# define fill_2(c, n) (*ptr++ = c, *ptr++ = '0' + (n) / 10, *ptr++ = '0' + (n) % 10)
5396 fill_2('-', tobj->vtm.mon);
5397 fill_2('-', tobj->vtm.mday);
5398 fill_2('T', tobj->vtm.hour);
5399 fill_2(':', tobj->vtm.min);
5400 fill_2(':', tobj->vtm.sec);
5401
5402 if (fraction_digits > 0) {
5403 VALUE subsecx = tobj->vtm.subsecx;
5404 long subsec;
5405 int digits = -1;
5406 *ptr++ = '.';
5407 if (fraction_digits <= TIME_SCALE_NUMDIGITS) {
5408 digits = TIME_SCALE_NUMDIGITS - (int)fraction_digits;
5409 }
5410 else {
5411 long w = fraction_digits - TIME_SCALE_NUMDIGITS; /* > 0 */
5412 subsecx = mulv(subsecx, rb_int_positive_pow(10, (unsigned long)w));
5413 if (!RB_INTEGER_TYPE_P(subsecx)) { /* maybe Rational */
5414 subsecx = rb_Integer(subsecx);
5415 }
5416 if (FIXNUM_P(subsecx)) digits = 0;
5417 }
5418 if (digits >= 0 && fraction_digits < INT_MAX) {
5419 subsec = NUM2LONG(subsecx);
5420 if (digits > 0) subsec /= (long)pow(10, digits);
5421 fill_digits_long(fraction_digits + 1, (int)fraction_digits, subsec) {
5422 RUBY_ASSERT(written == (int)fraction_digits);
5423 }
5424 }
5425 else {
5426 subsecx = rb_int2str(subsecx, 10);
5427 long len = RSTRING_LEN(subsecx);
5428 if (fraction_digits > len) {
5429 memset(ptr, '0', fraction_digits - len);
5430 }
5431 else {
5432 len = fraction_digits;
5433 }
5434 ptr += fraction_digits;
5435 memcpy(ptr - len, RSTRING_PTR(subsecx), len);
5436 }
5437 }
5438
5439 if (TZMODE_UTC_P(tobj)) {
5440 *ptr = 'Z';
5441 ptr++;
5442 }
5443 else {
5444 long offset = NUM2LONG(rb_time_utc_offset(time));
5445 char sign = offset < 0 ? '-' : '+';
5446 if (offset < 0) offset = -offset;
5447 offset /= 60;
5448 fill_2(sign, offset / 60);
5449 fill_2(':', offset % 60);
5450 }
5451 const char *const start = RSTRING_PTR(str);
5452 rb_str_set_len(str, ptr - start); // We could skip coderange scanning as we know it's full ASCII.
5453 return str;
5454}
5455
5456int ruby_marshal_write_long(long x, char *buf);
5457
5458enum {base_dump_size = 8};
5459
5460/* :nodoc: */
5461static VALUE
5462time_mdump(VALUE time)
5463{
5464 struct time_object *tobj;
5465 unsigned long p, s;
5466 char buf[base_dump_size + sizeof(long) + 1];
5467 int i;
5468 VALUE str;
5469
5470 struct vtm vtm;
5471 long year;
5472 long usec, nsec;
5473 VALUE subsecx, nano, subnano, v, zone;
5474
5475 VALUE year_extend = Qnil;
5476 const int max_year = 1900+0xffff;
5477
5478 GetTimeval(time, tobj);
5479
5480 gmtimew(tobj->timew, &vtm);
5481
5482 if (FIXNUM_P(vtm.year)) {
5483 year = FIX2LONG(vtm.year);
5484 if (year > max_year) {
5485 year_extend = INT2FIX(year - max_year);
5486 year = max_year;
5487 }
5488 else if (year < 1900) {
5489 year_extend = LONG2NUM(1900 - year);
5490 year = 1900;
5491 }
5492 }
5493 else {
5494 if (rb_int_positive_p(vtm.year)) {
5495 year_extend = rb_int_minus(vtm.year, INT2FIX(max_year));
5496 year = max_year;
5497 }
5498 else {
5499 year_extend = rb_int_minus(INT2FIX(1900), vtm.year);
5500 year = 1900;
5501 }
5502 }
5503
5504 subsecx = vtm.subsecx;
5505
5506 nano = mulquov(subsecx, INT2FIX(1000000000), INT2FIX(TIME_SCALE));
5507 divmodv(nano, INT2FIX(1), &v, &subnano);
5508 nsec = FIX2LONG(v);
5509 usec = nsec / 1000;
5510 nsec = nsec % 1000;
5511
5512 nano = addv(LONG2FIX(nsec), subnano);
5513
5514 p = 0x1UL << 31 | /* 1 */
5515 TZMODE_UTC_P(tobj) << 30 | /* 1 */
5516 (year-1900) << 14 | /* 16 */
5517 (vtm.mon-1) << 10 | /* 4 */
5518 vtm.mday << 5 | /* 5 */
5519 vtm.hour; /* 5 */
5520 s = (unsigned long)vtm.min << 26 | /* 6 */
5521 vtm.sec << 20 | /* 6 */
5522 usec; /* 20 */
5523
5524 for (i=0; i<4; i++) {
5525 buf[i] = (unsigned char)p;
5526 p = RSHIFT(p, 8);
5527 }
5528 for (i=4; i<8; i++) {
5529 buf[i] = (unsigned char)s;
5530 s = RSHIFT(s, 8);
5531 }
5532
5533 if (!NIL_P(year_extend)) {
5534 /*
5535 * Append extended year distance from 1900..(1900+0xffff). In
5536 * each cases, there is no sign as the value is positive. The
5537 * format is length (marshaled long) + little endian packed
5538 * binary (like as Integer).
5539 */
5540 size_t ysize = rb_absint_size(year_extend, NULL);
5541 char *p, *const buf_year_extend = buf + base_dump_size;
5542 if (ysize > LONG_MAX ||
5543 (i = ruby_marshal_write_long((long)ysize, buf_year_extend)) < 0) {
5544 rb_raise(rb_eArgError, "year too %s to marshal: %"PRIsVALUE" UTC",
5545 (year == 1900 ? "small" : "big"), vtm.year);
5546 }
5547 i += base_dump_size;
5548 str = rb_str_new(NULL, i + ysize);
5549 p = RSTRING_PTR(str);
5550 memcpy(p, buf, i);
5551 p += i;
5552 rb_integer_pack(year_extend, p, ysize, 1, 0, INTEGER_PACK_LITTLE_ENDIAN);
5553 }
5554 else {
5555 str = rb_str_new(buf, base_dump_size);
5556 }
5557 rb_copy_generic_ivar(str, time);
5558 if (!rb_equal(nano, INT2FIX(0))) {
5559 if (RB_TYPE_P(nano, T_RATIONAL)) {
5560 rb_ivar_set(str, id_nano_num, RRATIONAL(nano)->num);
5561 rb_ivar_set(str, id_nano_den, RRATIONAL(nano)->den);
5562 }
5563 else {
5564 rb_ivar_set(str, id_nano_num, nano);
5565 rb_ivar_set(str, id_nano_den, INT2FIX(1));
5566 }
5567 }
5568 if (nsec) { /* submicro is only for Ruby 1.9.1 compatibility */
5569 /*
5570 * submicro is formatted in fixed-point packed BCD (without sign).
5571 * It represent digits under microsecond.
5572 * For nanosecond resolution, 3 digits (2 bytes) are used.
5573 * However it can be longer.
5574 * Extra digits are ignored for loading.
5575 */
5576 char buf[2];
5577 int len = (int)sizeof(buf);
5578 buf[1] = (char)((nsec % 10) << 4);
5579 nsec /= 10;
5580 buf[0] = (char)(nsec % 10);
5581 nsec /= 10;
5582 buf[0] |= (char)((nsec % 10) << 4);
5583 if (buf[1] == 0)
5584 len = 1;
5585 rb_ivar_set(str, id_submicro, rb_str_new(buf, len));
5586 }
5587 if (!TZMODE_UTC_P(tobj)) {
5588 VALUE off = rb_time_utc_offset(time), div, mod;
5589 divmodv(off, INT2FIX(1), &div, &mod);
5590 if (rb_equal(mod, INT2FIX(0)))
5591 off = rb_Integer(div);
5592 rb_ivar_set(str, id_offset, off);
5593 }
5594 zone = tobj->vtm.zone;
5595 if (maybe_tzobj_p(zone)) {
5596 zone = rb_funcallv(zone, id_name, 0, 0);
5597 }
5598 rb_ivar_set(str, id_zone, zone);
5599 return str;
5600}
5601
5602/* :nodoc: */
5603static VALUE
5604time_dump(int argc, VALUE *argv, VALUE time)
5605{
5606 VALUE str;
5607
5608 rb_check_arity(argc, 0, 1);
5609 str = time_mdump(time);
5610
5611 return str;
5612}
5613
5614static VALUE
5615mload_findzone(VALUE arg)
5616{
5617 VALUE *argp = (VALUE *)arg;
5618 VALUE time = argp[0], zone = argp[1];
5619 return find_timezone(time, zone);
5620}
5621
5622static VALUE
5623mload_zone(VALUE time, VALUE zone)
5624{
5625 VALUE z, args[2];
5626 args[0] = time;
5627 args[1] = zone;
5628 z = rb_rescue(mload_findzone, (VALUE)args, 0, Qnil);
5629 if (NIL_P(z)) return rb_fstring(zone);
5630 if (RB_TYPE_P(z, T_STRING)) return rb_fstring(z);
5631 return z;
5632}
5633
5634long ruby_marshal_read_long(const char **buf, long len);
5635
5636/* :nodoc: */
5637static VALUE
5638time_mload(VALUE time, VALUE str)
5639{
5640 struct time_object *tobj;
5641 unsigned long p, s;
5642 time_t sec;
5643 long usec;
5644 unsigned char *buf;
5645 struct vtm vtm;
5646 int i, gmt;
5647 long nsec;
5648 VALUE submicro, nano_num, nano_den, offset, zone, year;
5649 wideval_t timew;
5650
5651 time_modify(time);
5652
5653#define get_attr(attr, iffound) \
5654 attr = rb_attr_delete(str, id_##attr); \
5655 if (!NIL_P(attr)) { \
5656 iffound; \
5657 }
5658
5659 get_attr(nano_num, {});
5660 get_attr(nano_den, {});
5661 get_attr(submicro, {});
5662 get_attr(offset, (offset = rb_rescue(validate_utc_offset, offset, 0, Qnil)));
5663 get_attr(zone, (zone = rb_rescue(validate_zone_name, zone, 0, Qnil)));
5664 get_attr(year, {});
5665
5666#undef get_attr
5667
5668 rb_copy_generic_ivar(time, str);
5669
5670 StringValue(str);
5671 buf = (unsigned char *)RSTRING_PTR(str);
5672 if (RSTRING_LEN(str) < base_dump_size) {
5673 goto invalid_format;
5674 }
5675
5676 p = s = 0;
5677 for (i=0; i<4; i++) {
5678 p |= (unsigned long)buf[i]<<(8*i);
5679 }
5680 for (i=4; i<8; i++) {
5681 s |= (unsigned long)buf[i]<<(8*(i-4));
5682 }
5683
5684 if ((p & (1UL<<31)) == 0) {
5685 gmt = 0;
5686 offset = Qnil;
5687 sec = p;
5688 usec = s;
5689 nsec = usec * 1000;
5690 timew = wadd(rb_time_magnify(TIMET2WV(sec)), wmulquoll(WINT2FIXWV(usec), TIME_SCALE, 1000000));
5691 }
5692 else {
5693 p &= ~(1UL<<31);
5694 gmt = (int)((p >> 30) & 0x1);
5695
5696 if (NIL_P(year)) {
5697 year = INT2FIX(((int)(p >> 14) & 0xffff) + 1900);
5698 }
5699 if (RSTRING_LEN(str) > base_dump_size) {
5700 long len = RSTRING_LEN(str) - base_dump_size;
5701 long ysize = 0;
5702 VALUE year_extend;
5703 const char *ybuf = (const char *)(buf += base_dump_size);
5704 ysize = ruby_marshal_read_long(&ybuf, len);
5705 len -= ybuf - (const char *)buf;
5706 if (ysize < 0 || ysize > len) goto invalid_format;
5707 year_extend = rb_integer_unpack(ybuf, ysize, 1, 0, INTEGER_PACK_LITTLE_ENDIAN);
5708 if (year == INT2FIX(1900)) {
5709 year = rb_int_minus(year, year_extend);
5710 }
5711 else {
5712 year = rb_int_plus(year, year_extend);
5713 }
5714 }
5715 unsigned int mon = ((int)(p >> 10) & 0xf); /* 0...12 */
5716 if (mon >= 12) {
5717 mon -= 12;
5718 year = addv(year, LONG2FIX(1));
5719 }
5720 vtm.year = year;
5721 vtm.mon = mon + 1;
5722 vtm.mday = (int)(p >> 5) & 0x1f;
5723 vtm.hour = (int) p & 0x1f;
5724 vtm.min = (int)(s >> 26) & 0x3f;
5725 vtm.sec = (int)(s >> 20) & 0x3f;
5726 vtm.utc_offset = INT2FIX(0);
5727 vtm.yday = vtm.wday = 0;
5728 vtm.isdst = 0;
5729 vtm.zone = str_empty;
5730
5731 usec = (long)(s & 0xfffff);
5732 nsec = usec * 1000;
5733
5734
5735 vtm.subsecx = mulquov(LONG2FIX(nsec), INT2FIX(TIME_SCALE), LONG2FIX(1000000000));
5736 if (nano_num != Qnil) {
5737 VALUE nano = quov(num_exact(nano_num), num_exact(nano_den));
5738 vtm.subsecx = addv(vtm.subsecx, mulquov(nano, INT2FIX(TIME_SCALE), LONG2FIX(1000000000)));
5739 }
5740 else if (submicro != Qnil) { /* for Ruby 1.9.1 compatibility */
5741 unsigned char *ptr;
5742 long len;
5743 int digit;
5744 ptr = (unsigned char*)StringValuePtr(submicro);
5745 len = RSTRING_LEN(submicro);
5746 nsec = 0;
5747 if (0 < len) {
5748 if (10 <= (digit = ptr[0] >> 4)) goto end_submicro;
5749 nsec += digit * 100;
5750 if (10 <= (digit = ptr[0] & 0xf)) goto end_submicro;
5751 nsec += digit * 10;
5752 }
5753 if (1 < len) {
5754 if (10 <= (digit = ptr[1] >> 4)) goto end_submicro;
5755 nsec += digit;
5756 }
5757 vtm.subsecx = addv(vtm.subsecx, mulquov(LONG2FIX(nsec), INT2FIX(TIME_SCALE), LONG2FIX(1000000000)));
5758end_submicro: ;
5759 }
5760 timew = timegmw(&vtm);
5761 }
5762
5763 GetNewTimeval(time, tobj);
5764 TZMODE_SET_LOCALTIME(tobj);
5765 tobj->vtm.tm_got = 0;
5766 time_set_timew(time, tobj, timew);
5767
5768 if (gmt) {
5769 TZMODE_SET_UTC(tobj);
5770 }
5771 else if (!NIL_P(offset)) {
5772 time_set_utc_offset(time, offset);
5773 time_fixoff(time);
5774 }
5775 if (!NIL_P(zone)) {
5776 zone = mload_zone(time, zone);
5777 RB_OBJ_WRITE(time, &tobj->vtm.zone, zone);
5778 zone_localtime(zone, time);
5779 }
5780
5781 return time;
5782
5783 invalid_format:
5784 rb_raise(rb_eTypeError, "marshaled time format differ");
5786}
5787
5788/* :nodoc: */
5789static VALUE
5790time_load(VALUE klass, VALUE str)
5791{
5792 VALUE time = time_s_alloc(klass);
5793
5794 time_mload(time, str);
5795 return time;
5796}
5797
5798/* :nodoc:*/
5799/* Document-class: Time::tm
5800 *
5801 * A container class for timezone conversion.
5802 */
5803
5804/*
5805 * call-seq:
5806 * Time::tm.from_time(t) -> tm
5807 *
5808 * Creates new Time::tm object from a Time object.
5809 */
5810
5811static VALUE
5812tm_from_time(VALUE klass, VALUE time)
5813{
5814 struct time_object *tobj;
5815 struct vtm vtm, *v;
5816 VALUE tm;
5817 struct time_object *ttm;
5818
5819 GetTimeval(time, tobj);
5820 tm = time_s_alloc(klass);
5821 ttm = RTYPEDDATA_GET_DATA(tm);
5822 v = &vtm;
5823
5824 wideval_t timew = tobj->timew;
5825 GMTIMEW(timew, v);
5826 time_set_timew(tm, ttm, wsub(timew, v2w(v->subsecx)));
5827 v->subsecx = INT2FIX(0);
5828 v->zone = Qnil;
5829 time_set_vtm(tm, ttm, *v);
5830
5831 ttm->vtm.tm_got = 1;
5832 TZMODE_SET_UTC(ttm);
5833 return tm;
5834}
5835
5836/*
5837 * call-seq:
5838 * Time::tm.new(year, month=nil, day=nil, hour=nil, min=nil, sec=nil, zone=nil) -> tm
5839 *
5840 * Creates new Time::tm object.
5841 */
5842
5843static VALUE
5844tm_initialize(int argc, VALUE *argv, VALUE time)
5845{
5846 struct vtm vtm;
5847 wideval_t t;
5848
5849 if (rb_check_arity(argc, 1, 7) > 6) argc = 6;
5850 time_arg(argc, argv, &vtm);
5851 t = timegmw(&vtm);
5852 struct time_object *tobj = RTYPEDDATA_GET_DATA(time);
5853 TZMODE_SET_UTC(tobj);
5854 time_set_timew(time, tobj, t);
5855 time_set_vtm(time, tobj, vtm);
5856
5857 return time;
5858}
5859
5860/* call-seq:
5861 * tm.to_time -> time
5862 *
5863 * Returns a new Time object.
5864 */
5865
5866static VALUE
5867tm_to_time(VALUE tm)
5868{
5869 struct time_object *torig = get_timeval(tm);
5870 VALUE dup = time_s_alloc(rb_cTime);
5871 struct time_object *tobj = RTYPEDDATA_GET_DATA(dup);
5872 *tobj = *torig;
5873 return dup;
5874}
5875
5876static VALUE
5877tm_plus(VALUE tm, VALUE offset)
5878{
5879 return time_add0(rb_obj_class(tm), get_timeval(tm), tm, offset, +1);
5880}
5881
5882static VALUE
5883tm_minus(VALUE tm, VALUE offset)
5884{
5885 return time_add0(rb_obj_class(tm), get_timeval(tm), tm, offset, -1);
5886}
5887
5888static VALUE
5889Init_tm(VALUE outer, const char *name)
5890{
5891 /* :stopdoc:*/
5892 VALUE tm;
5893 tm = rb_define_class_under(outer, name, rb_cObject);
5894 rb_define_alloc_func(tm, time_s_alloc);
5895 rb_define_method(tm, "sec", time_sec, 0);
5896 rb_define_method(tm, "min", time_min, 0);
5897 rb_define_method(tm, "hour", time_hour, 0);
5898 rb_define_method(tm, "mday", time_mday, 0);
5899 rb_define_method(tm, "day", time_mday, 0);
5900 rb_define_method(tm, "mon", time_mon, 0);
5901 rb_define_method(tm, "month", time_mon, 0);
5902 rb_define_method(tm, "year", time_year, 0);
5903 rb_define_method(tm, "isdst", time_isdst, 0);
5904 rb_define_method(tm, "dst?", time_isdst, 0);
5905 rb_define_method(tm, "zone", time_zone, 0);
5906 rb_define_method(tm, "gmtoff", rb_time_utc_offset, 0);
5907 rb_define_method(tm, "gmt_offset", rb_time_utc_offset, 0);
5908 rb_define_method(tm, "utc_offset", rb_time_utc_offset, 0);
5909 rb_define_method(tm, "utc?", time_utc_p, 0);
5910 rb_define_method(tm, "gmt?", time_utc_p, 0);
5911 rb_define_method(tm, "to_s", time_to_s, 0);
5912 rb_define_method(tm, "inspect", time_inspect, 0);
5913 rb_define_method(tm, "to_a", time_to_a, 0);
5914 rb_define_method(tm, "tv_sec", time_to_i, 0);
5915 rb_define_method(tm, "tv_usec", time_usec, 0);
5916 rb_define_method(tm, "usec", time_usec, 0);
5917 rb_define_method(tm, "tv_nsec", time_nsec, 0);
5918 rb_define_method(tm, "nsec", time_nsec, 0);
5919 rb_define_method(tm, "subsec", time_subsec, 0);
5920 rb_define_method(tm, "to_i", time_to_i, 0);
5921 rb_define_method(tm, "to_f", time_to_f, 0);
5922 rb_define_method(tm, "to_r", time_to_r, 0);
5923 rb_define_method(tm, "+", tm_plus, 1);
5924 rb_define_method(tm, "-", tm_minus, 1);
5925 rb_define_method(tm, "initialize", tm_initialize, -1);
5926 rb_define_method(tm, "utc", tm_to_time, 0);
5927 rb_alias(tm, rb_intern_const("to_time"), rb_intern_const("utc"));
5928 rb_define_singleton_method(tm, "from_time", tm_from_time, 1);
5929 /* :startdoc:*/
5930
5931 return tm;
5932}
5933
5934VALUE
5935rb_time_zone_abbreviation(VALUE zone, VALUE time)
5936{
5937 VALUE tm, abbr, strftime_args[2];
5938
5939 abbr = rb_check_string_type(zone);
5940 if (!NIL_P(abbr)) return abbr;
5941
5942 tm = tm_from_time(rb_cTimeTM, time);
5943 abbr = rb_check_funcall(zone, rb_intern("abbr"), 1, &tm);
5944 if (!UNDEF_P(abbr)) {
5945 goto found;
5946 }
5947#ifdef SUPPORT_TZINFO_ZONE_ABBREVIATION
5948 abbr = rb_check_funcall(zone, rb_intern("period_for_utc"), 1, &tm);
5949 if (!UNDEF_P(abbr)) {
5950 abbr = rb_funcallv(abbr, rb_intern("abbreviation"), 0, 0);
5951 goto found;
5952 }
5953#endif
5954 strftime_args[0] = rb_fstring_lit("%Z");
5955 strftime_args[1] = tm;
5956 abbr = rb_check_funcall(zone, rb_intern("strftime"), 2, strftime_args);
5957 if (!UNDEF_P(abbr)) {
5958 goto found;
5959 }
5960 abbr = rb_check_funcall_default(zone, idName, 0, 0, Qnil);
5961 found:
5962 return rb_obj_as_string(abbr);
5963}
5964
5965//
5966void
5967Init_Time(void)
5968{
5969#ifdef _WIN32
5970 ruby_reset_timezone(getenv("TZ"));
5971#endif
5972
5973 id_submicro = rb_intern_const("submicro");
5974 id_nano_num = rb_intern_const("nano_num");
5975 id_nano_den = rb_intern_const("nano_den");
5976 id_offset = rb_intern_const("offset");
5977 id_zone = rb_intern_const("zone");
5978 id_nanosecond = rb_intern_const("nanosecond");
5979 id_microsecond = rb_intern_const("microsecond");
5980 id_millisecond = rb_intern_const("millisecond");
5981 id_nsec = rb_intern_const("nsec");
5982 id_usec = rb_intern_const("usec");
5983 id_local_to_utc = rb_intern_const("local_to_utc");
5984 id_utc_to_local = rb_intern_const("utc_to_local");
5985 id_year = rb_intern_const("year");
5986 id_mon = rb_intern_const("mon");
5987 id_mday = rb_intern_const("mday");
5988 id_hour = rb_intern_const("hour");
5989 id_min = rb_intern_const("min");
5990 id_sec = rb_intern_const("sec");
5991 id_isdst = rb_intern_const("isdst");
5992 id_find_timezone = rb_intern_const("find_timezone");
5993
5994 sym_year = ID2SYM(rb_intern_const("year"));
5995 sym_month = ID2SYM(rb_intern_const("month"));
5996 sym_yday = ID2SYM(rb_intern_const("yday"));
5997 sym_wday = ID2SYM(rb_intern_const("wday"));
5998 sym_day = ID2SYM(rb_intern_const("day"));
5999 sym_hour = ID2SYM(rb_intern_const("hour"));
6000 sym_min = ID2SYM(rb_intern_const("min"));
6001 sym_sec = ID2SYM(rb_intern_const("sec"));
6002 sym_subsec = ID2SYM(rb_intern_const("subsec"));
6003 sym_dst = ID2SYM(rb_intern_const("dst"));
6004 sym_zone = ID2SYM(rb_intern_const("zone"));
6005
6006 str_utc = rb_fstring_lit("UTC");
6007 rb_vm_register_global_object(str_utc);
6008 str_empty = rb_fstring_lit("");
6009 rb_vm_register_global_object(str_empty);
6010
6011 rb_cTime = rb_define_class("Time", rb_cObject);
6014
6015 rb_define_alloc_func(rb_cTime, time_s_alloc);
6016 rb_define_singleton_method(rb_cTime, "utc", time_s_mkutc, -1);
6017 rb_define_singleton_method(rb_cTime, "local", time_s_mktime, -1);
6018 rb_define_alias(scTime, "gm", "utc");
6019 rb_define_alias(scTime, "mktime", "local");
6020
6021 rb_define_method(rb_cTime, "to_i", time_to_i, 0);
6022 rb_define_method(rb_cTime, "to_f", time_to_f, 0);
6023 rb_define_method(rb_cTime, "to_r", time_to_r, 0);
6024 rb_define_method(rb_cTime, "<=>", time_cmp, 1);
6025 rb_define_method(rb_cTime, "eql?", time_eql, 1);
6026 rb_define_method(rb_cTime, "hash", time_hash, 0);
6027 rb_define_method(rb_cTime, "initialize_copy", time_init_copy, 1);
6028
6029 rb_define_method(rb_cTime, "localtime", time_localtime_m, -1);
6030 rb_define_method(rb_cTime, "gmtime", time_gmtime, 0);
6031 rb_define_method(rb_cTime, "utc", time_gmtime, 0);
6032 rb_define_method(rb_cTime, "getlocal", time_getlocaltime, -1);
6033 rb_define_method(rb_cTime, "getgm", time_getgmtime, 0);
6034 rb_define_method(rb_cTime, "getutc", time_getgmtime, 0);
6035
6036 rb_define_method(rb_cTime, "ctime", time_asctime, 0);
6037 rb_define_method(rb_cTime, "asctime", time_asctime, 0);
6038 rb_define_method(rb_cTime, "to_s", time_to_s, 0);
6039 rb_define_method(rb_cTime, "inspect", time_inspect, 0);
6040 rb_define_method(rb_cTime, "to_a", time_to_a, 0);
6041 rb_define_method(rb_cTime, "deconstruct_keys", time_deconstruct_keys, 1);
6042
6043 rb_define_method(rb_cTime, "+", time_plus, 1);
6044 rb_define_method(rb_cTime, "-", time_minus, 1);
6045
6046 rb_define_method(rb_cTime, "round", time_round, -1);
6047 rb_define_method(rb_cTime, "floor", time_floor, -1);
6048 rb_define_method(rb_cTime, "ceil", time_ceil, -1);
6049
6050 rb_define_method(rb_cTime, "sec", time_sec, 0);
6051 rb_define_method(rb_cTime, "min", time_min, 0);
6052 rb_define_method(rb_cTime, "hour", time_hour, 0);
6053 rb_define_method(rb_cTime, "mday", time_mday, 0);
6054 rb_define_method(rb_cTime, "day", time_mday, 0);
6055 rb_define_method(rb_cTime, "mon", time_mon, 0);
6056 rb_define_method(rb_cTime, "month", time_mon, 0);
6057 rb_define_method(rb_cTime, "year", time_year, 0);
6058 rb_define_method(rb_cTime, "wday", time_wday, 0);
6059 rb_define_method(rb_cTime, "yday", time_yday, 0);
6060 rb_define_method(rb_cTime, "isdst", time_isdst, 0);
6061 rb_define_method(rb_cTime, "dst?", time_isdst, 0);
6062 rb_define_method(rb_cTime, "zone", time_zone, 0);
6063 rb_define_method(rb_cTime, "gmtoff", rb_time_utc_offset, 0);
6064 rb_define_method(rb_cTime, "gmt_offset", rb_time_utc_offset, 0);
6065 rb_define_method(rb_cTime, "utc_offset", rb_time_utc_offset, 0);
6066
6067 rb_define_method(rb_cTime, "utc?", time_utc_p, 0);
6068 rb_define_method(rb_cTime, "gmt?", time_utc_p, 0);
6069
6070 rb_define_method(rb_cTime, "sunday?", time_sunday, 0);
6071 rb_define_method(rb_cTime, "monday?", time_monday, 0);
6072 rb_define_method(rb_cTime, "tuesday?", time_tuesday, 0);
6073 rb_define_method(rb_cTime, "wednesday?", time_wednesday, 0);
6074 rb_define_method(rb_cTime, "thursday?", time_thursday, 0);
6075 rb_define_method(rb_cTime, "friday?", time_friday, 0);
6076 rb_define_method(rb_cTime, "saturday?", time_saturday, 0);
6077
6078 rb_define_method(rb_cTime, "tv_sec", time_to_i, 0);
6079 rb_define_method(rb_cTime, "tv_usec", time_usec, 0);
6080 rb_define_method(rb_cTime, "usec", time_usec, 0);
6081 rb_define_method(rb_cTime, "tv_nsec", time_nsec, 0);
6082 rb_define_method(rb_cTime, "nsec", time_nsec, 0);
6083 rb_define_method(rb_cTime, "subsec", time_subsec, 0);
6084
6085 rb_define_method(rb_cTime, "strftime", time_strftime, 1);
6086 rb_define_method(rb_cTime, "xmlschema", time_xmlschema, -1);
6087 rb_define_alias(rb_cTime, "iso8601", "xmlschema");
6088
6089 /* methods for marshaling */
6090 rb_define_private_method(rb_cTime, "_dump", time_dump, -1);
6091 rb_define_private_method(scTime, "_load", time_load, 1);
6092
6093 if (debug_find_time_numguess) {
6094 rb_define_hooked_variable("$find_time_numguess", (VALUE *)&find_time_numguess,
6095 find_time_numguess_getter, 0);
6096 }
6097
6098 rb_cTimeTM = Init_tm(rb_cTime, "tm");
6099}
6100
6101#include "timev.rbinc"
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
Definition assert.h:219
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
Definition class.c:1769
VALUE rb_singleton_class(VALUE obj)
Finds or creates the singleton class of the passed object.
Definition class.c:3051
void rb_define_alias(VALUE klass, const char *name1, const char *name2)
Defines an alias of a method.
Definition class.c:3094
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:3384
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define RB_INTEGER_TYPE_P
Old name of rb_integer_type_p.
Definition value_type.h:87
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define ISSPACE
Old name of rb_isspace.
Definition ctype.h:88
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define ID2SYM
Old name of RB_ID2SYM.
Definition symbol.h:44
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define T_STRUCT
Old name of RUBY_T_STRUCT.
Definition value_type.h:79
#define T_FIXNUM
Old name of RUBY_T_FIXNUM.
Definition value_type.h:63
#define UNREACHABLE_RETURN
Old name of RBIMPL_UNREACHABLE_RETURN.
Definition assume.h:29
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define LONG2FIX
Old name of RB_INT2FIX.
Definition long.h:49
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define ISDIGIT
Old name of rb_isdigit.
Definition ctype.h:93
#define ASSUME
Old name of RBIMPL_ASSUME.
Definition assume.h:27
#define T_RATIONAL
Old name of RUBY_T_RATIONAL.
Definition value_type.h:76
#define rb_ary_new3
Old name of rb_ary_new_from_args.
Definition array.h:658
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define STRNCASECMP
Old name of st_locale_insensitive_strncasecmp.
Definition ctype.h:103
#define ISASCII
Old name of rb_isascii.
Definition ctype.h:85
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition long_long.h:31
#define FIXNUM_MIN
Old name of RUBY_FIXNUM_MIN.
Definition fixnum.h:27
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define INT2NUM
Old name of RB_INT2NUM.
Definition int.h:43
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define CONST_ID
Old name of RUBY_CONST_ID.
Definition symbol.h:47
#define NUM2SIZET
Old name of RB_NUM2SIZE.
Definition size_t.h:61
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:678
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1477
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1473
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1471
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:1524
void rb_warning(const char *fmt,...)
Issues a warning.
Definition error.c:499
VALUE rb_cTime
Time class.
Definition time.c:702
VALUE rb_Float(VALUE val)
This is the logic behind Kernel#Float.
Definition object.c:3746
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
Definition object.c:3334
VALUE rb_cObject
Object class.
Definition object.c:60
VALUE rb_Integer(VALUE val)
This is the logic behind Kernel#Integer.
Definition object.c:3403
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:234
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:140
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:3328
#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
Encoding relates APIs.
static bool rb_enc_str_asciicompat_p(VALUE str)
Queries if the passed string is in an ASCII-compatible encoding.
Definition encoding.h:789
VALUE rb_enc_interned_str(const char *ptr, long len, rb_encoding *enc)
Identical to rb_enc_str_new(), except it returns a "f"string.
Definition string.c:14184
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1123
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
Definition vm_eval.c:1081
Defines RBIMPL_HAS_BUILTIN.
VALUE rb_check_array_type(VALUE obj)
Try converting an object to its array representation using its to_ary method, if any.
VALUE rb_ary_entry(VALUE ary, long off)
Queries an element of an array.
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition bignum.h:550
#define RB_INT_PARSE_SIGN
Allows a leading sign (+ or -).
Definition bignum.h:854
#define INTEGER_PACK_LITTLE_ENDIAN
Little endian combination.
Definition bignum.h:571
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
void rb_num_zerodiv(void)
Just always raises an exception.
Definition numeric.c:210
VALUE rb_int_positive_pow(long x, unsigned long y)
Raises the passed x to the power of y.
Definition numeric.c:4766
VALUE rb_rational_new(VALUE num, VALUE den)
Constructs a Rational, with reduction.
Definition rational.c:2006
#define rb_Rational1(x)
Shorthand of (x/1)r.
Definition rational.h:116
VALUE rb_str_subseq(VALUE str, long beg, long len)
Identical to rb_str_substr(), except the numbers are interpreted as byte offsets instead of character...
Definition string.c:3251
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1499
#define rb_usascii_str_new(str, len)
Identical to rb_str_new, except it generates a string of "US ASCII" encoding.
Definition string.h:1533
VALUE rb_str_dup(VALUE str)
Duplicates a string.
Definition string.c:2023
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
Definition string.c:3666
#define rb_usascii_str_new_cstr(str)
Identical to rb_str_new_cstr, except it generates a string of "US ASCII" encoding.
Definition string.h:1568
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3485
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:4135
#define rb_strlen_lit(str)
Length of a string literal.
Definition string.h:1693
VALUE rb_check_string_type(VALUE obj)
Try converting an object to its stringised representation using its to_str method,...
Definition string.c:3032
#define rb_str_cat_cstr(buf, str)
Identical to rb_str_cat(), except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1657
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
Definition string.h:1550
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2801
#define rb_str_new_cstr(str)
Identical to rb_str_new, except it assumes the passed pointer is a pointer to a C string.
Definition string.h:1515
VALUE rb_obj_as_string(VALUE obj)
Try converting an object to its stringised representation using its to_s method, if any.
Definition string.c:1887
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:2837
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:2845
struct timespec rb_time_timespec(VALUE time)
Identical to rb_time_timeval(), except for return type.
Definition time.c:3007
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:2828
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:2990
struct timeval rb_time_interval(VALUE num)
Creates a "time interval".
Definition time.c:2984
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:2868
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:5112
struct timespec rb_time_timespec_interval(VALUE num)
Identical to rb_time_interval(), except for return type.
Definition time.c:3021
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:2141
int rb_respond_to(VALUE obj, ID mid)
Queries if the object responds to the method.
Definition vm_method.c:3683
void rb_alias(VALUE klass, ID dst, ID src)
Resembles alias.
Definition vm_method.c:2936
VALUE rb_check_funcall(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it returns RUBY_Qundef instead of raising rb_eNoMethodError.
Definition vm_eval.c:691
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
Definition symbol.h:285
int off
Offset inside of ptr.
Definition io.h:5
int len
Length of the buffer.
Definition io.h:8
#define DECIMAL_SIZE_OF(expr)
An approximation of decimal representation size.
Definition util.h:48
#define rb_long2int
Just another name of rb_long2int_inline.
Definition long.h:62
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
void rb_define_hooked_variable(const char *q, VALUE *w, type *e, void_type *r)
Define a function-backended global variable.
VALUE rb_rescue(type *q, VALUE w, type *e, VALUE r)
An equivalent of rescue clause.
void rb_copy_generic_ivar(VALUE clone, VALUE obj)
Copies the list of instance variables.
Definition variable.c:2335
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:50
#define RARRAY_AREF(a, i)
Definition rarray.h:402
#define StringValue(v)
Ensures that the parameter object is a String.
Definition rstring.h:66
#define StringValuePtr(v)
Identical to StringValue, except it returns a char*.
Definition rstring.h:76
VALUE rb_str_export_locale(VALUE obj)
Identical to rb_str_export(), except it converts into the locale encoding instead.
Definition string.c:1478
static char * RSTRING_END(VALUE str)
Queries the end of the contents pointer of the string.
Definition rstring.h:409
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
#define RUBY_TYPED_DEFAULT_FREE
This is a value you can set to rb_data_type_struct::dfree.
Definition rtypeddata.h:81
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:773
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
Definition rtypeddata.h:604
#define RTEST
This is an old name of RB_TEST.
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:242
const char * wrap_struct_name
Name of structs of this kind.
Definition rtypeddata.h:249
Definition timev.h:5
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
Definition value.h:63
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static bool rb_integer_type_p(VALUE obj)
Queries if the object is an instance of rb_cInteger.
Definition value_type.h:204
static bool RB_TYPE_P(VALUE obj, enum ruby_value_type t)
Queries if the given object is of given type.
Definition value_type.h:376