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