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