Ruby 2.0.0p247(2013-06-27revision41674)

- Main Page
- Modules
- Data Structures
- Files

- File List
- Globals

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