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