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