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