Ruby: time.c Source File

Ruby 4.0.5p0 (2026-05-20 revision 64336ffd0ee9e1f4c05891695a3d7b49cb709721)

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